hugo commited on
Commit
c3e7ef9
·
1 Parent(s): 3b5897d

Last version

Browse files
events.out.tfevents.1636537590.t1v-n-8a498248-w-0.35743.3.v2 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:e7c9e989c989b63fa5680318cf7d50e3629bfe46288fb7d11d2ccd86ec4d5a44
3
- size 46267077
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18f5efe8c40c97fee8beded37d50122d3f18bc4fd1d93364ae4c0de2606265bb
3
+ size 46999218
flax_model.msgpack CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ba4074f093f9fde8477bc27e798502738407d8f8f5bcf16434429a1739993070
3
  size 1198558445
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1dbb3a56a3fa60487e09fa14da853b219c33329331e03f1d08a631b0cb3c7e0
3
  size 1198558445
run_t5_mlm_flax.py ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Pretraining the library models for T5-like span-masked language modeling on a text file or a dataset.
18
+
19
+ Here is the full list of checkpoints on the hub that can be pretrained by this script:
20
+ https://huggingface.co/models?filter=t5
21
+ """
22
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
23
+ import logging
24
+ import os
25
+ import gc
26
+ import sys
27
+ import time
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+ from typing import Dict, List, Optional
31
+
32
+ import numpy as np
33
+ from datasets import load_dataset
34
+ from tqdm import tqdm
35
+
36
+ import flax
37
+ import jax
38
+ import jax.numpy as jnp
39
+ import optax
40
+ from flax import jax_utils, traverse_util
41
+ from flax.training import train_state
42
+ from flax.training.common_utils import get_metrics, onehot, shard
43
+ from huggingface_hub import Repository
44
+ from transformers import (
45
+ CONFIG_MAPPING,
46
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
47
+ AutoTokenizer,
48
+ BatchEncoding,
49
+ FlaxT5ForConditionalGeneration,
50
+ HfArgumentParser,
51
+ PreTrainedTokenizerBase,
52
+ T5Config,
53
+ TrainingArguments,
54
+ is_tensorboard_available,
55
+ set_seed,
56
+ )
57
+ from transformers.file_utils import get_full_repo_name
58
+ from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
59
+
60
+
61
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
62
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
63
+
64
+
65
+ @dataclass
66
+ class ModelArguments:
67
+ """
68
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
69
+ """
70
+
71
+ model_name_or_path: Optional[str] = field(
72
+ default=None,
73
+ metadata={
74
+ "help": "The model checkpoint for weights initialization."
75
+ "Don't set if you want to train a model from scratch."
76
+ },
77
+ )
78
+ model_type: Optional[str] = field(
79
+ default=None,
80
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
81
+ )
82
+ config_name: Optional[str] = field(
83
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
84
+ )
85
+ tokenizer_name: Optional[str] = field(
86
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
87
+ )
88
+ cache_dir: Optional[str] = field(
89
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
90
+ )
91
+ use_fast_tokenizer: bool = field(
92
+ default=True,
93
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
94
+ )
95
+ dtype: Optional[str] = field(
96
+ default="float32",
97
+ metadata={
98
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
99
+ },
100
+ )
101
+
102
+
103
+ @dataclass
104
+ class DataTrainingArguments:
105
+ """
106
+ Arguments pertaining to what data we are going to input our model for training and eval.
107
+ """
108
+
109
+ dataset_name: Optional[str] = field(
110
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
111
+ )
112
+ dataset_config_name: Optional[str] = field(
113
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
114
+ )
115
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
116
+ validation_file: Optional[str] = field(
117
+ default=None,
118
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
119
+ )
120
+ train_ref_file: Optional[str] = field(
121
+ default=None,
122
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
123
+ )
124
+ validation_ref_file: Optional[str] = field(
125
+ default=None,
126
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
127
+ )
128
+ overwrite_cache: bool = field(
129
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
130
+ )
131
+ validation_split_percentage: Optional[int] = field(
132
+ default=5,
133
+ metadata={
134
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
135
+ },
136
+ )
137
+ max_seq_length: Optional[int] = field(
138
+ default=None,
139
+ metadata={
140
+ "help": "The maximum total input sequence length after tokenization and masking. Sequences longer than this will be truncated. Default to the max input length of the model."
141
+ },
142
+ )
143
+ preprocessing_num_workers: Optional[int] = field(
144
+ default=None,
145
+ metadata={"help": "The number of processes to use for the preprocessing."},
146
+ )
147
+ mlm_probability: float = field(
148
+ default=0.15, metadata={"help": "Ratio of tokens to mask for span masked language modeling loss"}
149
+ )
150
+ mean_noise_span_length: float = field(
151
+ default=3.0,
152
+ metadata={"help": "Mean span length of masked tokens"},
153
+ )
154
+
155
+ def __post_init__(self):
156
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
157
+ raise ValueError("Need either a dataset name or a training/validation file.")
158
+ else:
159
+ if self.train_file is not None:
160
+ extension = self.train_file.split(".")[-1]
161
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
162
+ if self.validation_file is not None:
163
+ extension = self.validation_file.split(".")[-1]
164
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
165
+
166
+
167
+ def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):
168
+ """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2466>`__ .
169
+
170
+ Training parameters to avoid padding with random_spans_noise_mask.
171
+ When training a model with random_spans_noise_mask, we would like to set the other
172
+ training hyperparmeters in a way that avoids padding.
173
+ This function helps us compute these hyperparameters.
174
+ We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
175
+ and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
176
+ This function tells us the required number of tokens in the raw example (for split_tokens())
177
+ as well as the length of the encoded targets. Note that this function assumes
178
+ the inputs and targets will have EOS appended and includes that in the reported length.
179
+
180
+ Args:
181
+ inputs_length: an integer - desired length of the tokenized inputs sequence
182
+ noise_density: a float
183
+ mean_noise_span_length: a float
184
+ Returns:
185
+ tokens_length: length of original text in tokens
186
+ targets_length: an integer - length in tokens of encoded targets sequence
187
+ """
188
+
189
+ def _tokens_length_to_inputs_length_targets_length(tokens_length):
190
+ num_noise_tokens = int(round(tokens_length * noise_density))
191
+ num_nonnoise_tokens = tokens_length - num_noise_tokens
192
+ num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
193
+ # inputs contain all nonnoise tokens, sentinels for all noise spans
194
+ # and one EOS token.
195
+ _input_length = num_nonnoise_tokens + num_noise_spans + 1
196
+ _output_length = num_noise_tokens + num_noise_spans + 1
197
+ return _input_length, _output_length
198
+
199
+ tokens_length = inputs_length
200
+
201
+ while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
202
+ tokens_length += 1
203
+
204
+ inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
205
+
206
+ # minor hack to get the targets length to be equal to inputs length
207
+ # which is more likely to have been set to a nice round number.
208
+ if noise_density == 0.5 and targets_length > inputs_length:
209
+ tokens_length -= 1
210
+ targets_length -= 1
211
+ return tokens_length, targets_length
212
+
213
+
214
+ @flax.struct.dataclass
215
+ class FlaxDataCollatorForT5MLM:
216
+ """
217
+ Data collator used for T5 span-masked language modeling.
218
+ It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
219
+ For more information on how T5 span-masked language modeling works, one can take a look
220
+ at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
221
+ or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
222
+
223
+ Args:
224
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
225
+ The tokenizer used for encoding the data.
226
+ noise_density (:obj:`float`):
227
+ The probability with which to (randomly) mask tokens in the input.
228
+ mean_noise_span_length (:obj:`float`):
229
+ The average span length of the masked tokens.
230
+ input_length (:obj:`int`):
231
+ The expected input length after masking.
232
+ target_length (:obj:`int`):
233
+ The expected target length after masking.
234
+ pad_token_id: (:obj:`int`):
235
+ The pad token id of the model
236
+ decoder_start_token_id: (:obj:`int):
237
+ The decoder start token id of the model
238
+ """
239
+
240
+ tokenizer: PreTrainedTokenizerBase
241
+ noise_density: float
242
+ mean_noise_span_length: float
243
+ input_length: int
244
+ target_length: int
245
+ pad_token_id: int
246
+ decoder_start_token_id: int
247
+
248
+ def __call__(self, examples: List[Dict[str, np.ndarray]]) -> Dict[str, np.ndarray]:
249
+
250
+ # convert list to dict and tensorize input
251
+ batch = BatchEncoding(
252
+ {k: np.array([examples[i][k] for i in range(len(examples))]) for k, v in examples[0].items()}
253
+ )
254
+
255
+ input_ids = batch["input_ids"]
256
+ batch_size, expandend_input_length = input_ids.shape
257
+
258
+ mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
259
+ labels_mask = ~mask_indices
260
+
261
+ input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
262
+ labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
263
+
264
+ batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
265
+ batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
266
+
267
+ if batch["input_ids"].shape[-1] != self.input_length:
268
+ raise ValueError(
269
+ f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but should be {self.target_length}."
270
+ )
271
+
272
+ if batch["labels"].shape[-1] != self.target_length:
273
+ raise ValueError(
274
+ f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be {self.target_length}."
275
+ )
276
+
277
+ # to check that tokens are correctly proprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
278
+ batch["decoder_input_ids"] = shift_tokens_right(
279
+ batch["labels"], self.pad_token_id, self.decoder_start_token_id
280
+ )
281
+
282
+ return batch
283
+
284
+ def create_sentinel_ids(self, mask_indices):
285
+ """
286
+ Sentinel ids creation given the indices that should be masked.
287
+ The start indices of each mask are replaced by the sentinel ids in increasing
288
+ order. Consecutive mask indices to be deleted are replaced with `-1`.
289
+ """
290
+ start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
291
+ start_indices[:, 0] = mask_indices[:, 0]
292
+
293
+ sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
294
+ sentinel_ids = np.where(sentinel_ids != 0, (sentinel_ids + self.tokenizer.vocab_size - 1), 0)
295
+ sentinel_ids -= mask_indices - start_indices
296
+
297
+ return sentinel_ids
298
+
299
+ def filter_input_ids(self, input_ids, sentinel_ids):
300
+ """
301
+ Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
302
+ This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
303
+ """
304
+ batch_size = input_ids.shape[0]
305
+
306
+ input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
307
+ input_ids = input_ids_full[input_ids_full > 0].reshape((batch_size, -1))
308
+ input_ids = np.concatenate(
309
+ [input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
310
+ )
311
+ return input_ids
312
+
313
+ def random_spans_noise_mask(self, length):
314
+
315
+ """This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-transfer-transformer/blob/84f8bcc14b5f2c03de51bd3587609ba8f6bbd1cd/t5/data/preprocessors.py#L2682>`__ .
316
+
317
+ Noise mask consisting of random spans of noise tokens.
318
+ The number of noise tokens and the number of noise spans and non-noise spans
319
+ are determined deterministically as follows:
320
+ num_noise_tokens = round(length * noise_density)
321
+ num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
322
+ Spans alternate between non-noise and noise, beginning with non-noise.
323
+ Subject to the above restrictions, all masks are equally likely.
324
+
325
+ Args:
326
+ length: an int32 scalar (length of the incoming token sequence)
327
+ noise_density: a float - approximate density of output mask
328
+ mean_noise_span_length: a number
329
+
330
+ Returns:
331
+ a boolean tensor with shape [length]
332
+ """
333
+
334
+ orig_length = length
335
+
336
+ num_noise_tokens = int(np.round(length * self.noise_density))
337
+ # avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
338
+ num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
339
+ num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
340
+
341
+ # avoid degeneracy by ensuring positive number of noise spans
342
+ num_noise_spans = max(num_noise_spans, 1)
343
+ num_nonnoise_tokens = length - num_noise_tokens
344
+
345
+ # pick the lengths of the noise spans and the non-noise spans
346
+ def _random_segmentation(num_items, num_segments):
347
+ """Partition a sequence of items randomly into non-empty segments.
348
+ Args:
349
+ num_items: an integer scalar > 0
350
+ num_segments: an integer scalar in [1, num_items]
351
+ Returns:
352
+ a Tensor with shape [num_segments] containing positive integers that add
353
+ up to num_items
354
+ """
355
+ mask_indices = np.arange(num_items - 1) < (num_segments - 1)
356
+ np.random.shuffle(mask_indices)
357
+ first_in_segment = np.pad(mask_indices, [[1, 0]])
358
+ segment_id = np.cumsum(first_in_segment)
359
+ # count length of sub segments assuming that list is sorted
360
+ _, segment_length = np.unique(segment_id, return_counts=True)
361
+ return segment_length
362
+
363
+ noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
364
+ nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
365
+
366
+ interleaved_span_lengths = np.reshape(
367
+ np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
368
+ )
369
+ span_starts = np.cumsum(interleaved_span_lengths)[:-1]
370
+ span_start_indicator = np.zeros((length,), dtype=np.int8)
371
+ span_start_indicator[span_starts] = True
372
+ span_num = np.cumsum(span_start_indicator)
373
+ is_noise = np.equal(span_num % 2, 1)
374
+
375
+ return is_noise[:orig_length]
376
+
377
+
378
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
379
+ num_samples = len(samples_idx)
380
+ samples_to_remove = num_samples % batch_size
381
+
382
+ if samples_to_remove != 0:
383
+ samples_idx = samples_idx[:-samples_to_remove]
384
+ sections_split = num_samples // batch_size
385
+ batch_idx = jnp.split(samples_idx, sections_split)
386
+ return batch_idx
387
+
388
+
389
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
390
+ summary_writer.scalar("train_time", train_time, step)
391
+
392
+ train_metrics = get_metrics(train_metrics)
393
+ for key, vals in train_metrics.items():
394
+ tag = f"train_{key}"
395
+ for i, val in enumerate(vals):
396
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
397
+
398
+
399
+ def write_eval_metric(summary_writer, eval_metrics, step):
400
+ for metric_name, value in eval_metrics.items():
401
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
402
+
403
+
404
+ if __name__ == "__main__":
405
+ # See all possible arguments in src/transformers/training_args.py
406
+ # or by passing the --help flag to this script.
407
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
408
+
409
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
410
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
411
+ # If we pass only one argument to the script and it's the path to a json file,
412
+ # let's parse it to get our arguments.
413
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
414
+ else:
415
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
416
+
417
+ if (
418
+ os.path.exists(training_args.output_dir)
419
+ and os.listdir(training_args.output_dir)
420
+ and training_args.do_train
421
+ and not training_args.overwrite_output_dir
422
+ ):
423
+ raise ValueError(
424
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
425
+ "Use --overwrite_output_dir to overcome."
426
+ )
427
+
428
+ # Setup logging
429
+ logging.basicConfig(
430
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
431
+ level="NOTSET",
432
+ datefmt="[%X]",
433
+ )
434
+
435
+ # Log on each process the small summary:
436
+ logger = logging.getLogger(__name__)
437
+
438
+ # Set the verbosity to info of the Transformers logger (on main process only):
439
+ logger.info(f"Training/evaluation parameters {training_args}")
440
+
441
+ # Set seed before initializing model.
442
+ set_seed(training_args.seed)
443
+
444
+ # Handle the repository creation
445
+ if training_args.push_to_hub:
446
+ if training_args.hub_model_id is None:
447
+ repo_name = get_full_repo_name(
448
+ Path(training_args.output_dir).absolute().name, token=training_args.hub_token
449
+ )
450
+ else:
451
+ repo_name = training_args.hub_model_id
452
+ repo = Repository(training_args.output_dir, clone_from=repo_name)
453
+
454
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
455
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
456
+ # (the dataset will be downloaded automatically from the datasets Hub).
457
+ #
458
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
459
+ # 'text' is found. You can easily tweak this behavior (see below).
460
+ if data_args.dataset_name is not None:
461
+ # Downloading and loading a dataset from the hub.
462
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
463
+
464
+ if "validation" not in datasets.keys():
465
+ datasets["validation"] = load_dataset(
466
+ data_args.dataset_name,
467
+ data_args.dataset_config_name,
468
+ split=f"train[:{data_args.validation_split_percentage}%]",
469
+ cache_dir=model_args.cache_dir,
470
+ )
471
+ datasets["train"] = load_dataset(
472
+ data_args.dataset_name,
473
+ data_args.dataset_config_name,
474
+ split=f"train[{data_args.validation_split_percentage}%:]",
475
+ cache_dir=model_args.cache_dir,
476
+ )
477
+ else:
478
+ data_files = {}
479
+ if data_args.train_file is not None:
480
+ data_files["train"] = data_args.train_file
481
+ if data_args.validation_file is not None:
482
+ data_files["validation"] = data_args.validation_file
483
+ extension = data_args.train_file.split(".")[-1]
484
+ if extension == "txt":
485
+ extension = "text"
486
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
487
+
488
+ if "validation" not in datasets.keys():
489
+ datasets["validation"] = load_dataset(
490
+ extension,
491
+ data_files=data_files,
492
+ split=f"train[:{data_args.validation_split_percentage}%]",
493
+ cache_dir=model_args.cache_dir,
494
+ )
495
+ datasets["train"] = load_dataset(
496
+ extension,
497
+ data_files=data_files,
498
+ split=f"train[{data_args.validation_split_percentage}%:]",
499
+ cache_dir=model_args.cache_dir,
500
+ )
501
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
502
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
503
+
504
+ # Load pretrained model and tokenizer
505
+
506
+ if model_args.tokenizer_name:
507
+ tokenizer = AutoTokenizer.from_pretrained(
508
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
509
+ )
510
+ elif model_args.model_name_or_path:
511
+ tokenizer = AutoTokenizer.from_pretrained(
512
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
513
+ )
514
+ else:
515
+ raise ValueError(
516
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
517
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
518
+ )
519
+
520
+ if model_args.config_name:
521
+ config = T5Config.from_pretrained(
522
+ model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
523
+ )
524
+ elif model_args.model_name_or_path:
525
+ config = T5Config.from_pretrained(
526
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
527
+ )
528
+ else:
529
+ config = CONFIG_MAPPING[model_args.model_type]()
530
+ logger.warning("You are instantiating a new config instance from scratch.")
531
+
532
+ # Preprocessing the datasets.
533
+ # First we tokenize all the texts.
534
+ if training_args.do_train:
535
+ column_names = datasets["train"].column_names
536
+ else:
537
+ column_names = datasets["validation"].column_names
538
+ text_column_name = "text" if "text" in column_names else column_names[0]
539
+
540
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
541
+
542
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
543
+ # Since we make sure that all sequences are of the same length, no attention_mask is needed.
544
+ def tokenize_function(examples):
545
+ return tokenizer(examples[text_column_name], return_attention_mask=False)
546
+
547
+ tokenized_datasets = datasets.map(
548
+ tokenize_function,
549
+ batched=True,
550
+ num_proc=data_args.preprocessing_num_workers,
551
+ remove_columns=column_names,
552
+ load_from_cache_file=not data_args.overwrite_cache,
553
+ cache_file_names={
554
+ 'train': '/mnt/datasets/huggingface/train-pt-10m-tokenize.arrow',
555
+ 'validation': '/mnt/datasets/huggingface/train-pt-10m-tokenize-val.arrow',
556
+ },
557
+ )
558
+
559
+
560
+ # T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
561
+ # To ensure that the input length is `max_seq_length`, we need to increase the maximum length
562
+ # according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
563
+ expanded_inputs_length, targets_length = compute_input_and_target_lengths(
564
+ inputs_length=max_seq_length,
565
+ noise_density=data_args.mlm_probability,
566
+ mean_noise_span_length=data_args.mean_noise_span_length,
567
+ )
568
+
569
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length.
570
+ def group_texts(examples):
571
+ # Concatenate all texts.
572
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
573
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
574
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
575
+ # customize this part to your needs.
576
+ if total_length >= expanded_inputs_length:
577
+ total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
578
+ # Split by chunks of max_len.
579
+ result = {
580
+ k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
581
+ for k, t in concatenated_examples.items()
582
+ }
583
+ return result
584
+
585
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
586
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
587
+ # might be slower to preprocess.
588
+ #
589
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
590
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
591
+ tokenized_datasets = tokenized_datasets.map(
592
+ group_texts,
593
+ batched=True,
594
+ num_proc=data_args.preprocessing_num_workers,
595
+ load_from_cache_file=not data_args.overwrite_cache,
596
+ desc='Grouping',
597
+ cache_file_names={
598
+ 'train': '/mnt/datasets/huggingface/train-pt-10m-group.arrow',
599
+ 'validation': '/mnt/datasets/huggingface/train-pt-10m-group-val.arrow',
600
+ },
601
+ )
602
+
603
+ # Enable tensorboard only on the master node
604
+ has_tensorboard = is_tensorboard_available()
605
+ if has_tensorboard and jax.process_index() == 0:
606
+ try:
607
+ from flax.metrics.tensorboard import SummaryWriter
608
+
609
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
610
+ except ImportError as ie:
611
+ has_tensorboard = False
612
+ logger.warning(
613
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
614
+ )
615
+ else:
616
+ logger.warning(
617
+ "Unable to display metrics through TensorBoard because the package is not installed: "
618
+ "Please run pip install tensorboard to enable."
619
+ )
620
+
621
+ # Initialize our training
622
+ rng = jax.random.PRNGKey(training_args.seed)
623
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
624
+
625
+ if model_args.model_name_or_path:
626
+ model = FlaxT5ForConditionalGeneration.from_pretrained(
627
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
628
+ )
629
+ else:
630
+ model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
631
+
632
+ # Data collator
633
+ # This one will take care of randomly masking the tokens.
634
+ data_collator = FlaxDataCollatorForT5MLM(
635
+ tokenizer=tokenizer,
636
+ noise_density=data_args.mlm_probability,
637
+ mean_noise_span_length=data_args.mean_noise_span_length,
638
+ input_length=max_seq_length,
639
+ target_length=targets_length,
640
+ pad_token_id=model.config.pad_token_id,
641
+ decoder_start_token_id=model.config.decoder_start_token_id,
642
+ )
643
+
644
+ # Store some constant
645
+ num_epochs = int(training_args.num_train_epochs)
646
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
647
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
648
+
649
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
650
+
651
+ # Create learning rate schedule
652
+ warmup_fn = optax.linear_schedule(
653
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
654
+ )
655
+ decay_fn = optax.linear_schedule(
656
+ init_value=training_args.learning_rate,
657
+ end_value=0,
658
+ transition_steps=num_train_steps - training_args.warmup_steps,
659
+ )
660
+ linear_decay_lr_schedule_fn = optax.join_schedules(
661
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
662
+ )
663
+
664
+ # We use Optax's "masking" functionality to not apply weight decay
665
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
666
+ # mask boolean with the same structure as the parameters.
667
+ # The mask is True for parameters that should be decayed.
668
+ def decay_mask_fn(params):
669
+ flat_params = traverse_util.flatten_dict(params)
670
+ flat_mask = {
671
+ path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
672
+ for path in flat_params
673
+ }
674
+ return traverse_util.unflatten_dict(flat_mask)
675
+
676
+ # create adam optimizer
677
+ if training_args.adafactor:
678
+ # We use the default parameters here to initialize adafactor,
679
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
680
+ optimizer = optax.adafactor(
681
+ learning_rate=linear_decay_lr_schedule_fn,
682
+ )
683
+ else:
684
+ optimizer = optax.adamw(
685
+ learning_rate=linear_decay_lr_schedule_fn,
686
+ b1=training_args.adam_beta1,
687
+ b2=training_args.adam_beta2,
688
+ weight_decay=training_args.weight_decay,
689
+ mask=decay_mask_fn,
690
+ )
691
+
692
+ # Setup train state
693
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
694
+
695
+ # Define gradient update step fn
696
+ def train_step(state, batch, dropout_rng):
697
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
698
+
699
+ def loss_fn(params):
700
+ labels = batch.pop("labels")
701
+
702
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
703
+
704
+ # compute loss
705
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
706
+
707
+ return loss
708
+
709
+ grad_fn = jax.value_and_grad(loss_fn)
710
+ loss, grad = grad_fn(state.params)
711
+ grad = jax.lax.pmean(grad, "batch")
712
+ new_state = state.apply_gradients(grads=grad)
713
+
714
+ metrics = jax.lax.pmean(
715
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
716
+ )
717
+
718
+ return new_state, metrics, new_dropout_rng
719
+
720
+ # Create parallel version of the train step
721
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
722
+
723
+ # Define eval fn
724
+ def eval_step(params, batch):
725
+ labels = batch.pop("labels")
726
+
727
+ logits = model(**batch, params=params, train=False)[0]
728
+
729
+ # compute loss
730
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
731
+
732
+ # compute accuracy
733
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
734
+
735
+ # summarize metrics
736
+ metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
737
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
738
+
739
+ return metrics
740
+
741
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
742
+
743
+ # Replicate the train state on each device
744
+ state = jax_utils.replicate(state)
745
+
746
+ gc.collect()
747
+
748
+ print(tokenized_datasets)
749
+
750
+ train_time = 0
751
+ epochs = tqdm(range(num_epochs), desc="Epoch ... ", position=0)
752
+ for epoch in epochs:
753
+ # ======================== Training ================================
754
+ train_start = time.time()
755
+ train_metrics = []
756
+
757
+ # Create sampling rng
758
+ rng, input_rng = jax.random.split(rng)
759
+
760
+ # Generate an epoch by shuffling sampling indices from the train dataset
761
+ num_train_samples = 5_000_000 # len(tokenized_datasets["train"])
762
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
763
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
764
+
765
+ # Gather the indexes for creating the batch and do a training step
766
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
767
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
768
+ model_inputs = data_collator(samples)
769
+
770
+ # Model forward
771
+ model_inputs = shard(model_inputs.data)
772
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
773
+ train_metrics.append(train_metric)
774
+
775
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
776
+
777
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
778
+ # Save metrics
779
+ train_metric = jax_utils.unreplicate(train_metric)
780
+ train_time += time.time() - train_start
781
+ if has_tensorboard and jax.process_index() == 0:
782
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
783
+
784
+ epochs.write(
785
+ f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
786
+ )
787
+
788
+ train_metrics = []
789
+
790
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
791
+ # ======================== Evaluating ==============================
792
+ num_eval_samples = len(tokenized_datasets["validation"])
793
+ eval_samples_idx = jnp.arange(num_eval_samples)
794
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
795
+
796
+ eval_metrics = []
797
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
798
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
799
+ model_inputs = data_collator(samples)
800
+
801
+ # Model forward
802
+ model_inputs = shard(model_inputs.data)
803
+ metrics = p_eval_step(state.params, model_inputs)
804
+ eval_metrics.append(metrics)
805
+
806
+ # get eval metrics
807
+ eval_metrics = get_metrics(eval_metrics)
808
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
809
+
810
+ # Update progress bar
811
+ epochs.write(f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})")
812
+
813
+ # Save metrics
814
+ if has_tensorboard and jax.process_index() == 0:
815
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
816
+
817
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
818
+ # save checkpoint after each epoch and push checkpoint to the hub
819
+ if jax.process_index() == 0:
820
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
821
+ model.save_pretrained(training_args.output_dir, params=params)
822
+ tokenizer.save_pretrained(training_args.output_dir)
823
+ if training_args.push_to_hub:
824
+ repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False)