pere commited on
Commit
f1564ec
1 Parent(s): 0f1e8ce
README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: no
3
+ license: cc-by-4.0
4
+ tags:
5
+ - seq2seq
6
+ datasets:
7
+ - Norwegian Nynorsk/Bokmål
8
+ ---
9
+ # 🇳🇴 Norwegian T5 Base model Trained on the NCC🇳🇴
10
+
11
+ This is a Norwegian T5-base model trained on the Norwegian Colossal Corpus (NCC) on a TPU v3-8. It needs to be finetuned on a specific task before being used for anything.
12
+
13
+ Currently the model is training. It is expected that it should be finished by the end of August 2021.
14
+
15
+ The following setting were used in training:
16
+ ```bash
17
+ ./run_t5_mlm_flax_streaming.py \
18
+ --output_dir="./" \
19
+ --model_type="t5" \
20
+ --config_name="./" \
21
+ --tokenizer_name="./" \
22
+ --dataset_name="pere/norwegian_colossal_corpus_v2_short100k" \
23
+ --max_seq_length="512" \
24
+ --weight_decay="0.01" \
25
+ --per_device_train_batch_size="32" \
26
+ --per_device_eval_batch_size="32" \
27
+ --learning_rate="8e-3" \
28
+ --warmup_steps="5000" \
29
+ --overwrite_output_dir \
30
+ --cache_dir /mnt/disks/flaxdisk/cache/ \
31
+ --num_train_epochs="5" \
32
+ --adam_beta1="0.9" \
33
+ --adam_beta2="0.98" \
34
+ --logging_steps="500" \
35
+ --num_train_steps="1000000" \
36
+ --num_eval_samples="5000" \
37
+ --save_steps="5000" \
38
+ --eval_steps="5000" \
39
+ --preprocessing_num_workers 96 \
40
+ --adafactor \
41
+ --push_to_hub
42
+ ```
added_tokens.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"<extra_id_98>": 50101, "<extra_id_26>": 50029, "<extra_id_8>": 50011, "<extra_id_56>": 50059, "<extra_id_29>": 50032, "<extra_id_75>": 50078, "<extra_id_36>": 50039, "<extra_id_86>": 50089, "<extra_id_16>": 50019, "<extra_id_42>": 50045, "<extra_id_6>": 50009, "<extra_id_14>": 50017, "<extra_id_2>": 50005, "<extra_id_53>": 50056, "<extra_id_7>": 50010, "<extra_id_88>": 50091, "<extra_id_32>": 50035, "<extra_id_18>": 50021, "<extra_id_37>": 50040, "<extra_id_24>": 50027, "<extra_id_68>": 50071, "<extra_id_92>": 50095, "<extra_id_33>": 50036, "<extra_id_60>": 50063, "<extra_id_99>": 50102, "<extra_id_59>": 50062, "<extra_id_77>": 50080, "<extra_id_15>": 50018, "<extra_id_10>": 50013, "<extra_id_45>": 50048, "<extra_id_31>": 50034, "<extra_id_0>": 50003, "<extra_id_58>": 50061, "<extra_id_48>": 50051, "<extra_id_74>": 50077, "<extra_id_47>": 50050, "<extra_id_82>": 50085, "<extra_id_61>": 50064, "<extra_id_46>": 50049, "<extra_id_96>": 50099, "<extra_id_78>": 50081, "<extra_id_50>": 50053, "<extra_id_90>": 50093, "<extra_id_11>": 50014, "<extra_id_22>": 50025, "<extra_id_65>": 50068, "<extra_id_63>": 50066, "<extra_id_89>": 50092, "<extra_id_17>": 50020, "<extra_id_28>": 50031, "<extra_id_43>": 50046, "<extra_id_13>": 50016, "<extra_id_84>": 50087, "<extra_id_21>": 50024, "<extra_id_64>": 50067, "<extra_id_76>": 50079, "<extra_id_23>": 50026, "<extra_id_79>": 50082, "<extra_id_67>": 50070, "<extra_id_3>": 50006, "<extra_id_62>": 50065, "<extra_id_19>": 50022, "<extra_id_27>": 50030, "<extra_id_55>": 50058, "<extra_id_73>": 50076, "<extra_id_87>": 50090, "<extra_id_54>": 50057, "<extra_id_83>": 50086, "<extra_id_91>": 50094, "<extra_id_35>": 50038, "<extra_id_30>": 50033, "<extra_id_49>": 50052, "<extra_id_72>": 50075, "<extra_id_94>": 50097, "<extra_id_69>": 50072, "<extra_id_25>": 50028, "<extra_id_71>": 50074, "<extra_id_80>": 50083, "<extra_id_93>": 50096, "<extra_id_57>": 50060, "<extra_id_95>": 50098, "<extra_id_97>": 50100, "<extra_id_41>": 50044, "<extra_id_20>": 50023, "<extra_id_5>": 50008, "<extra_id_34>": 50037, "<extra_id_81>": 50084, "<extra_id_85>": 50088, "<extra_id_51>": 50054, "<extra_id_52>": 50055, "<extra_id_4>": 50007, "<extra_id_9>": 50012, "<extra_id_1>": 50004, "<extra_id_44>": 50047, "<extra_id_66>": 50069, "<extra_id_40>": 50043, "<extra_id_70>": 50073, "<extra_id_12>": 50015, "<extra_id_38>": 50041, "<extra_id_39>": 50042}
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./",
3
+ "architectures": [
4
+ "T5ForConditionalGeneration"
5
+ ],
6
+ "d_ff": 2048,
7
+ "d_kv": 64,
8
+ "d_model": 768,
9
+ "decoder_start_token_id": 0,
10
+ "dropout_rate": 0.1,
11
+ "eos_token_id": 1,
12
+ "feed_forward_proj": "gated-gelu",
13
+ "gradient_checkpointing": false,
14
+ "initializer_factor": 1.0,
15
+ "is_encoder_decoder": true,
16
+ "layer_norm_epsilon": 1e-06,
17
+ "model_type": "t5",
18
+ "num_decoder_layers": 12,
19
+ "num_heads": 12,
20
+ "num_layers": 12,
21
+ "output_past": true,
22
+ "pad_token_id": 0,
23
+ "relative_attention_num_buckets": 32,
24
+ "tie_word_embeddings": false,
25
+ "torch_dtype": "float32",
26
+ "transformers_version": "4.11.0.dev0",
27
+ "use_cache": true,
28
+ "vocab_size": 50103
29
+ }
events.out.tfevents.1639128144.t1v-n-358ff5d1-w-0.682754.3.v2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f1216e4980e1dd6c1efd39cd067c51abef8fa5d755c58b8530ae1a06df87467
3
+ size 40
events.out.tfevents.1639128215.t1v-n-358ff5d1-w-0.684069.3.v2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b813e267dec940c53c60ddefdb2f4d0e6eb05913d71b01fdb62ac010ec42886
3
+ size 40
events.out.tfevents.1639128449.t1v-n-358ff5d1-w-0.685544.3.v2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5028f346d399c3fc9719115e79c9861d0fbb50a27f5fba7ec0db5a2554443837
3
+ size 40
run.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ./run_t5_mlm_flax_streaming.py \
2
+ --output_dir="./" \
3
+ --model_type="t5" \
4
+ --config_name="./" \
5
+ --tokenizer_name="./" \
6
+ --dataset_name="NbAiLab/nbailab_extended" \
7
+ --max_seq_length="512" \
8
+ --weight_decay="0.01" \
9
+ --per_device_train_batch_size="32" \
10
+ --per_device_eval_batch_size="32" \
11
+ --learning_rate="8e-3" \
12
+ --warmup_steps="2000" \
13
+ --overwrite_output_dir \
14
+ --cache_dir /mnt/disks/flaxdisk/cache/ \
15
+ --num_train_steps="1000000" \
16
+ --adam_beta1="0.9" \
17
+ --adam_beta2="0.98" \
18
+ --logging_steps="5000" \
19
+ --save_steps="5000" \
20
+ --eval_steps="5000" \
21
+ --preprocessing_num_workers="64" \
22
+ --push_to_hub
23
+
run_mlm_flax.py ADDED
@@ -0,0 +1,691 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for masked language modeling (BERT, ALBERT, RoBERTa...) with whole word masking on a
18
+ text file or a dataset.
19
+
20
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
21
+ https://huggingface.co/models?filter=masked-lm
22
+ """
23
+ import logging
24
+ import os
25
+ import sys
26
+ import time
27
+ from dataclasses import dataclass, field
28
+
29
+ # You can also adapt this script on your own masked language modeling task. Pointers for this are left as comments.
30
+ from pathlib import Path
31
+ from typing import Dict, List, Optional, Tuple
32
+
33
+ import numpy as np
34
+ from datasets import load_dataset
35
+ from tqdm import tqdm
36
+
37
+ import flax
38
+ import jax
39
+ import jax.numpy as jnp
40
+ import optax
41
+ from flax import jax_utils, traverse_util
42
+ from flax.training import train_state
43
+ from flax.training.common_utils import get_metrics, onehot, shard
44
+ from transformers import (
45
+ CONFIG_MAPPING,
46
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
47
+ AutoConfig,
48
+ AutoTokenizer,
49
+ FlaxAutoModelForMaskedLM,
50
+ HfArgumentParser,
51
+ PreTrainedTokenizerBase,
52
+ TensorType,
53
+ TrainingArguments,
54
+ is_tensorboard_available,
55
+ set_seed,
56
+ )
57
+
58
+
59
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
60
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
61
+
62
+
63
+ @dataclass
64
+ class ModelArguments:
65
+ """
66
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
67
+ """
68
+
69
+ model_name_or_path: Optional[str] = field(
70
+ default=None,
71
+ metadata={
72
+ "help": "The model checkpoint for weights initialization."
73
+ "Don't set if you want to train a model from scratch."
74
+ },
75
+ )
76
+ model_type: Optional[str] = field(
77
+ default=None,
78
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
79
+ )
80
+ config_name: Optional[str] = field(
81
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
82
+ )
83
+ tokenizer_name: Optional[str] = field(
84
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
85
+ )
86
+ cache_dir: Optional[str] = field(
87
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
88
+ )
89
+ use_fast_tokenizer: bool = field(
90
+ default=True,
91
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
92
+ )
93
+ dtype: Optional[str] = field(
94
+ default="float32",
95
+ metadata={
96
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
97
+ },
98
+ )
99
+
100
+
101
+ @dataclass
102
+ class DataTrainingArguments:
103
+ """
104
+ Arguments pertaining to what data we are going to input our model for training and eval.
105
+ """
106
+
107
+ dataset_name: Optional[str] = field(
108
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
109
+ )
110
+ dataset_config_name: Optional[str] = field(
111
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
112
+ )
113
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
114
+ validation_file: Optional[str] = field(
115
+ default=None,
116
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
117
+ )
118
+ train_ref_file: Optional[str] = field(
119
+ default=None,
120
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
121
+ )
122
+ validation_ref_file: Optional[str] = field(
123
+ default=None,
124
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
125
+ )
126
+ overwrite_cache: bool = field(
127
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
128
+ )
129
+ validation_split_percentage: Optional[int] = field(
130
+ default=5,
131
+ metadata={
132
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
133
+ },
134
+ )
135
+ max_seq_length: Optional[int] = field(
136
+ default=None,
137
+ metadata={
138
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
139
+ "than this will be truncated. Default to the max input length of the model."
140
+ },
141
+ )
142
+ preprocessing_num_workers: Optional[int] = field(
143
+ default=None,
144
+ metadata={"help": "The number of processes to use for the preprocessing."},
145
+ )
146
+ mlm_probability: float = field(
147
+ default=0.15, metadata={"help": "Ratio of tokens to mask for masked language modeling loss"}
148
+ )
149
+ pad_to_max_length: bool = field(
150
+ default=False,
151
+ metadata={
152
+ "help": "Whether to pad all samples to `max_seq_length`. "
153
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
154
+ },
155
+ )
156
+ line_by_line: bool = field(
157
+ default=False,
158
+ metadata={"help": "Whether distinct lines of text in the dataset are to be handled as distinct sequences."},
159
+ )
160
+
161
+ def __post_init__(self):
162
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
163
+ raise ValueError("Need either a dataset name or a training/validation file.")
164
+ else:
165
+ if self.train_file is not None:
166
+ extension = self.train_file.split(".")[-1]
167
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
168
+ if self.validation_file is not None:
169
+ extension = self.validation_file.split(".")[-1]
170
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
171
+
172
+
173
+ @flax.struct.dataclass
174
+ class FlaxDataCollatorForLanguageModeling:
175
+ """
176
+ Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
177
+ are not all of the same length.
178
+
179
+ Args:
180
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
181
+ The tokenizer used for encoding the data.
182
+ mlm_probability (:obj:`float`, `optional`, defaults to 0.15):
183
+ The probability with which to (randomly) mask tokens in the input.
184
+
185
+ .. note::
186
+
187
+ For best performance, this data collator should be used with a dataset having items that are dictionaries or
188
+ BatchEncoding, with the :obj:`"special_tokens_mask"` key, as returned by a
189
+ :class:`~transformers.PreTrainedTokenizer` or a :class:`~transformers.PreTrainedTokenizerFast` with the
190
+ argument :obj:`return_special_tokens_mask=True`.
191
+ """
192
+
193
+ tokenizer: PreTrainedTokenizerBase
194
+ mlm_probability: float = 0.15
195
+
196
+ def __post_init__(self):
197
+ if self.tokenizer.mask_token is None:
198
+ raise ValueError(
199
+ "This tokenizer does not have a mask token which is necessary for masked language modeling. "
200
+ "You should pass `mlm=False` to train on causal language modeling instead."
201
+ )
202
+
203
+ def __call__(self, examples: List[Dict[str, np.ndarray]], pad_to_multiple_of: int) -> Dict[str, np.ndarray]:
204
+ # Handle dict or lists with proper padding and conversion to tensor.
205
+ batch = self.tokenizer.pad(examples, pad_to_multiple_of=pad_to_multiple_of, return_tensors=TensorType.NUMPY)
206
+
207
+ # If special token mask has been preprocessed, pop it from the dict.
208
+ special_tokens_mask = batch.pop("special_tokens_mask", None)
209
+
210
+ batch["input_ids"], batch["labels"] = self.mask_tokens(
211
+ batch["input_ids"], special_tokens_mask=special_tokens_mask
212
+ )
213
+ return batch
214
+
215
+ def mask_tokens(
216
+ self, inputs: np.ndarray, special_tokens_mask: Optional[np.ndarray]
217
+ ) -> Tuple[jnp.ndarray, jnp.ndarray]:
218
+ """
219
+ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
220
+ """
221
+ labels = inputs.copy()
222
+ # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
223
+ probability_matrix = np.full(labels.shape, self.mlm_probability)
224
+ special_tokens_mask = special_tokens_mask.astype("bool")
225
+
226
+ probability_matrix[special_tokens_mask] = 0.0
227
+ masked_indices = np.random.binomial(1, probability_matrix).astype("bool")
228
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
229
+
230
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
231
+ indices_replaced = np.random.binomial(1, np.full(labels.shape, 0.8)).astype("bool") & masked_indices
232
+ inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
233
+
234
+ # 10% of the time, we replace masked input tokens with random word
235
+ indices_random = np.random.binomial(1, np.full(labels.shape, 0.5)).astype("bool")
236
+ indices_random &= masked_indices & ~indices_replaced
237
+
238
+ random_words = np.random.randint(self.tokenizer.vocab_size, size=labels.shape, dtype="i4")
239
+ inputs[indices_random] = random_words[indices_random]
240
+
241
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
242
+ return inputs, labels
243
+
244
+
245
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
246
+ num_samples = len(samples_idx)
247
+ samples_to_remove = num_samples % batch_size
248
+
249
+ if samples_to_remove != 0:
250
+ samples_idx = samples_idx[:-samples_to_remove]
251
+ sections_split = num_samples // batch_size
252
+ batch_idx = np.split(samples_idx, sections_split)
253
+ return batch_idx
254
+
255
+
256
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
257
+ summary_writer.scalar("train_time", train_time, step)
258
+
259
+ train_metrics = get_metrics(train_metrics)
260
+ for key, vals in train_metrics.items():
261
+ tag = f"train_{key}"
262
+ for i, val in enumerate(vals):
263
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
264
+
265
+
266
+ def write_eval_metric(summary_writer, eval_metrics, step):
267
+ for metric_name, value in eval_metrics.items():
268
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
269
+
270
+
271
+ if __name__ == "__main__":
272
+ # See all possible arguments in src/transformers/training_args.py
273
+ # or by passing the --help flag to this script.
274
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
275
+
276
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
277
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
278
+ # If we pass only one argument to the script and it's the path to a json file,
279
+ # let's parse it to get our arguments.
280
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
281
+ else:
282
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
283
+
284
+ if (
285
+ os.path.exists(training_args.output_dir)
286
+ and os.listdir(training_args.output_dir)
287
+ and training_args.do_train
288
+ and not training_args.overwrite_output_dir
289
+ ):
290
+ raise ValueError(
291
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
292
+ "Use --overwrite_output_dir to overcome."
293
+ )
294
+
295
+ # Setup logging
296
+ logging.basicConfig(
297
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
298
+ level="NOTSET",
299
+ datefmt="[%X]",
300
+ )
301
+
302
+ # Log on each process the small summary:
303
+ logger = logging.getLogger(__name__)
304
+
305
+ # Set the verbosity to info of the Transformers logger (on main process only):
306
+ logger.info(f"Training/evaluation parameters {training_args}")
307
+
308
+ # Set seed before initializing model.
309
+ set_seed(training_args.seed)
310
+
311
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
312
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
313
+ # (the dataset will be downloaded automatically from the datasets Hub).
314
+ #
315
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
316
+ # 'text' is found. You can easily tweak this behavior (see below).
317
+ #
318
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
319
+ # download the dataset.
320
+ if data_args.dataset_name is not None:
321
+ # Downloading and loading a dataset from the hub.
322
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
323
+
324
+ if "validation" not in datasets.keys():
325
+ datasets["validation"] = load_dataset(
326
+ data_args.dataset_name,
327
+ data_args.dataset_config_name,
328
+ split=f"train[:{data_args.validation_split_percentage}%]",
329
+ cache_dir=model_args.cache_dir,
330
+ )
331
+ datasets["train"] = load_dataset(
332
+ data_args.dataset_name,
333
+ data_args.dataset_config_name,
334
+ split=f"train[{data_args.validation_split_percentage}%:]",
335
+ cache_dir=model_args.cache_dir,
336
+ )
337
+ else:
338
+ data_files = {}
339
+ if data_args.train_file is not None:
340
+ data_files["train"] = data_args.train_file
341
+ if data_args.validation_file is not None:
342
+ data_files["validation"] = data_args.validation_file
343
+ extension = data_args.train_file.split(".")[-1]
344
+ if extension == "txt":
345
+ extension = "text"
346
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
347
+
348
+ if "validation" not in datasets.keys():
349
+ datasets["validation"] = load_dataset(
350
+ extension,
351
+ data_files=data_files,
352
+ split=f"train[:{data_args.validation_split_percentage}%]",
353
+ cache_dir=model_args.cache_dir,
354
+ )
355
+ datasets["train"] = load_dataset(
356
+ extension,
357
+ data_files=data_files,
358
+ split=f"train[{data_args.validation_split_percentage}%:]",
359
+ cache_dir=model_args.cache_dir,
360
+ )
361
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
362
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
363
+
364
+ # Load pretrained model and tokenizer
365
+
366
+ # Distributed training:
367
+ # The .from_pretrained methods guarantee that only one local process can concurrently
368
+ # download model & vocab.
369
+ if model_args.config_name:
370
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
371
+ elif model_args.model_name_or_path:
372
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
373
+ else:
374
+ config = CONFIG_MAPPING[model_args.model_type]()
375
+ logger.warning("You are instantiating a new config instance from scratch.")
376
+
377
+ if model_args.tokenizer_name:
378
+ tokenizer = AutoTokenizer.from_pretrained(
379
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
380
+ )
381
+ elif model_args.model_name_or_path:
382
+ tokenizer = AutoTokenizer.from_pretrained(
383
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
384
+ )
385
+ else:
386
+ raise ValueError(
387
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
388
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
389
+ )
390
+
391
+ # Preprocessing the datasets.
392
+ # First we tokenize all the texts.
393
+ if training_args.do_train:
394
+ column_names = datasets["train"].column_names
395
+ else:
396
+ column_names = datasets["validation"].column_names
397
+ text_column_name = "text" if "text" in column_names else column_names[0]
398
+
399
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
400
+
401
+ if data_args.line_by_line:
402
+ # When using line_by_line, we just tokenize each nonempty line.
403
+ padding = "max_length" if data_args.pad_to_max_length else False
404
+
405
+ def tokenize_function(examples):
406
+ # Remove empty lines
407
+ examples = [line for line in examples if len(line) > 0 and not line.isspace()]
408
+ return tokenizer(
409
+ examples,
410
+ return_special_tokens_mask=True,
411
+ padding=padding,
412
+ truncation=True,
413
+ max_length=max_seq_length,
414
+ )
415
+
416
+ tokenized_datasets = datasets.map(
417
+ tokenize_function,
418
+ input_columns=[text_column_name],
419
+ batched=True,
420
+ num_proc=data_args.preprocessing_num_workers,
421
+ remove_columns=column_names,
422
+ load_from_cache_file=not data_args.overwrite_cache,
423
+ )
424
+
425
+ else:
426
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
427
+ # We use `return_special_tokens_mask=True` because DataCollatorForLanguageModeling (see below) is more
428
+ # efficient when it receives the `special_tokens_mask`.
429
+ def tokenize_function(examples):
430
+ return tokenizer(examples[text_column_name], return_special_tokens_mask=True)
431
+
432
+ tokenized_datasets = datasets.map(
433
+ tokenize_function,
434
+ batched=True,
435
+ num_proc=data_args.preprocessing_num_workers,
436
+ remove_columns=column_names,
437
+ load_from_cache_file=not data_args.overwrite_cache,
438
+ )
439
+
440
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of
441
+ # max_seq_length.
442
+ def group_texts(examples):
443
+ # Concatenate all texts.
444
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
445
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
446
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
447
+ # customize this part to your needs.
448
+ if total_length >= max_seq_length:
449
+ total_length = (total_length // max_seq_length) * max_seq_length
450
+ # Split by chunks of max_len.
451
+ result = {
452
+ k: [t[i : i + max_seq_length] for i in range(0, total_length, max_seq_length)]
453
+ for k, t in concatenated_examples.items()
454
+ }
455
+ return result
456
+
457
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
458
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
459
+ # might be slower to preprocess.
460
+ #
461
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
462
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
463
+ tokenized_datasets = tokenized_datasets.map(
464
+ group_texts,
465
+ batched=True,
466
+ num_proc=data_args.preprocessing_num_workers,
467
+ load_from_cache_file=not data_args.overwrite_cache,
468
+ )
469
+
470
+ # Enable tensorboard only on the master node
471
+ has_tensorboard = is_tensorboard_available()
472
+ if has_tensorboard and jax.process_index() == 0:
473
+ try:
474
+ from flax.metrics.tensorboard import SummaryWriter
475
+
476
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
477
+ except ImportError as ie:
478
+ has_tensorboard = False
479
+ logger.warning(
480
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
481
+ )
482
+ else:
483
+ logger.warning(
484
+ "Unable to display metrics through TensorBoard because the package is not installed: "
485
+ "Please run pip install tensorboard to enable."
486
+ )
487
+
488
+ # Data collator
489
+ # This one will take care of randomly masking the tokens.
490
+ data_collator = FlaxDataCollatorForLanguageModeling(tokenizer=tokenizer, mlm_probability=data_args.mlm_probability)
491
+
492
+ # Initialize our training
493
+ rng = jax.random.PRNGKey(training_args.seed)
494
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
495
+
496
+ if model_args.model_name_or_path:
497
+ model = FlaxAutoModelForMaskedLM.from_pretrained(
498
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
499
+ )
500
+ else:
501
+ model = FlaxAutoModelForMaskedLM.from_config(
502
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
503
+ )
504
+
505
+ # Store some constant
506
+ num_epochs = int(training_args.num_train_epochs)
507
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
508
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
509
+
510
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
511
+
512
+ # Create learning rate schedule
513
+ warmup_fn = optax.linear_schedule(
514
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
515
+ )
516
+ decay_fn = optax.linear_schedule(
517
+ init_value=training_args.learning_rate,
518
+ end_value=0,
519
+ transition_steps=num_train_steps - training_args.warmup_steps,
520
+ )
521
+ linear_decay_lr_schedule_fn = optax.join_schedules(
522
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
523
+ )
524
+
525
+ # We use Optax's "masking" functionality to not apply weight decay
526
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
527
+ # mask boolean with the same structure as the parameters.
528
+ # The mask is True for parameters that should be decayed.
529
+ # Note that this mask is specifically adapted for FlaxBERT-like models.
530
+ # For other models, one should correct the layer norm parameter naming
531
+ # accordingly.
532
+ def decay_mask_fn(params):
533
+ flat_params = traverse_util.flatten_dict(params)
534
+ flat_mask = {path: (path[-1] != "bias" and path[-2:] != ("LayerNorm", "scale")) for path in flat_params}
535
+ return traverse_util.unflatten_dict(flat_mask)
536
+
537
+ # create adam optimizer
538
+ if training_args.adafactor:
539
+ # We use the default parameters here to initialize adafactor,
540
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
541
+ optimizer = optax.adafactor(
542
+ learning_rate=linear_decay_lr_schedule_fn,
543
+ )
544
+ else:
545
+ optimizer = optax.adamw(
546
+ learning_rate=linear_decay_lr_schedule_fn,
547
+ b1=training_args.adam_beta1,
548
+ b2=training_args.adam_beta2,
549
+ eps=training_args.adam_epsilon,
550
+ weight_decay=training_args.weight_decay,
551
+ mask=decay_mask_fn,
552
+ )
553
+
554
+ # Setup train state
555
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
556
+
557
+ # Define gradient update step fn
558
+ def train_step(state, batch, dropout_rng):
559
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
560
+
561
+ def loss_fn(params):
562
+ labels = batch.pop("labels")
563
+
564
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
565
+
566
+ # compute loss, ignore padded input tokens
567
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
568
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
569
+
570
+ # take average
571
+ loss = loss.sum() / label_mask.sum()
572
+
573
+ return loss
574
+
575
+ grad_fn = jax.value_and_grad(loss_fn)
576
+ loss, grad = grad_fn(state.params)
577
+ grad = jax.lax.pmean(grad, "batch")
578
+ new_state = state.apply_gradients(grads=grad)
579
+
580
+ metrics = jax.lax.pmean(
581
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
582
+ )
583
+
584
+ return new_state, metrics, new_dropout_rng
585
+
586
+ # Create parallel version of the train step
587
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
588
+
589
+ # Define eval fn
590
+ def eval_step(params, batch):
591
+ labels = batch.pop("labels")
592
+
593
+ logits = model(**batch, params=params, train=False)[0]
594
+
595
+ # compute loss, ignore padded input tokens
596
+ label_mask = jnp.where(labels > 0, 1.0, 0.0)
597
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])) * label_mask
598
+
599
+ # compute accuracy
600
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels) * label_mask
601
+
602
+ # summarize metrics
603
+ metrics = {"loss": loss.sum(), "accuracy": accuracy.sum(), "normalizer": label_mask.sum()}
604
+ metrics = jax.lax.psum(metrics, axis_name="batch")
605
+
606
+ return metrics
607
+
608
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
609
+
610
+ # Replicate the train state on each device
611
+ state = jax_utils.replicate(state)
612
+
613
+ train_time = 0
614
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
615
+ for epoch in epochs:
616
+ # ======================== Training ================================
617
+ train_start = time.time()
618
+ train_metrics = []
619
+
620
+ # Create sampling rng
621
+ rng, input_rng = jax.random.split(rng)
622
+
623
+ # Generate an epoch by shuffling sampling indices from the train dataset
624
+ num_train_samples = len(tokenized_datasets["train"])
625
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
626
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
627
+
628
+ # Gather the indexes for creating the batch and do a training step
629
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
630
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
631
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
632
+
633
+ # Model forward
634
+ model_inputs = shard(model_inputs.data)
635
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
636
+ train_metrics.append(train_metric)
637
+
638
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
639
+
640
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
641
+ # Save metrics
642
+ train_metric = jax_utils.unreplicate(train_metric)
643
+ train_time += time.time() - train_start
644
+ if has_tensorboard and jax.process_index() == 0:
645
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
646
+
647
+ epochs.write(
648
+ f"Step... ({cur_step} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
649
+ )
650
+
651
+ train_metrics = []
652
+
653
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
654
+ # ======================== Evaluating ==============================
655
+ num_eval_samples = len(tokenized_datasets["validation"])
656
+ eval_samples_idx = jnp.arange(num_eval_samples)
657
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
658
+
659
+ eval_metrics = []
660
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
661
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
662
+ model_inputs = data_collator(samples, pad_to_multiple_of=16)
663
+
664
+ # Model forward
665
+ model_inputs = shard(model_inputs.data)
666
+ metrics = p_eval_step(state.params, model_inputs)
667
+ eval_metrics.append(metrics)
668
+
669
+ # normalize eval metrics
670
+ eval_metrics = get_metrics(eval_metrics)
671
+ eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
672
+ eval_normalizer = eval_metrics.pop("normalizer")
673
+ eval_metrics = jax.tree_map(lambda x: x / eval_normalizer, eval_metrics)
674
+
675
+ # Update progress bar
676
+ epochs.desc = f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
677
+
678
+ # Save metrics
679
+ if has_tensorboard and jax.process_index() == 0:
680
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
681
+
682
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
683
+ # save checkpoint after each epoch and push checkpoint to the hub
684
+ if jax.process_index() == 0:
685
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
686
+ model.save_pretrained(
687
+ training_args.output_dir,
688
+ params=params,
689
+ push_to_hub=training_args.push_to_hub,
690
+ commit_message=f"Saving weights and logs of step {cur_step}",
691
+ )
run_t5_mlm_flax.py ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
26
+ import time
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+ from typing import Dict, List, Optional
30
+
31
+ import numpy as np
32
+ from datasets import load_dataset
33
+ from tqdm import tqdm
34
+
35
+ import flax
36
+ import jax
37
+ import jax.numpy as jnp
38
+ import optax
39
+ from flax import jax_utils, traverse_util
40
+ from flax.training import train_state
41
+ from flax.training.common_utils import get_metrics, onehot, shard
42
+ from transformers import (
43
+ CONFIG_MAPPING,
44
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
45
+ AutoTokenizer,
46
+ BatchEncoding,
47
+ FlaxT5ForConditionalGeneration,
48
+ HfArgumentParser,
49
+ PreTrainedTokenizerBase,
50
+ T5Config,
51
+ TrainingArguments,
52
+ is_tensorboard_available,
53
+ set_seed,
54
+ )
55
+ from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
56
+
57
+
58
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
59
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
60
+
61
+
62
+ @dataclass
63
+ class ModelArguments:
64
+ """
65
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
66
+ """
67
+
68
+ model_name_or_path: Optional[str] = field(
69
+ default=None,
70
+ metadata={
71
+ "help": "The model checkpoint for weights initialization."
72
+ "Don't set if you want to train a model from scratch."
73
+ },
74
+ )
75
+ model_type: Optional[str] = field(
76
+ default=None,
77
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
78
+ )
79
+ config_name: Optional[str] = field(
80
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
81
+ )
82
+ tokenizer_name: Optional[str] = field(
83
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
84
+ )
85
+ cache_dir: Optional[str] = field(
86
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
87
+ )
88
+ use_fast_tokenizer: bool = field(
89
+ default=True,
90
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
91
+ )
92
+ dtype: Optional[str] = field(
93
+ default="float32",
94
+ metadata={
95
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
96
+ },
97
+ )
98
+
99
+
100
+ @dataclass
101
+ class DataTrainingArguments:
102
+ """
103
+ Arguments pertaining to what data we are going to input our model for training and eval.
104
+ """
105
+
106
+ dataset_name: Optional[str] = field(
107
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
108
+ )
109
+ dataset_config_name: Optional[str] = field(
110
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
111
+ )
112
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
113
+ validation_file: Optional[str] = field(
114
+ default=None,
115
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
116
+ )
117
+ train_ref_file: Optional[str] = field(
118
+ default=None,
119
+ metadata={"help": "An optional input train ref data file for whole word masking in Chinese."},
120
+ )
121
+ validation_ref_file: Optional[str] = field(
122
+ default=None,
123
+ metadata={"help": "An optional input validation ref data file for whole word masking in Chinese."},
124
+ )
125
+ overwrite_cache: bool = field(
126
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
127
+ )
128
+ validation_split_percentage: Optional[int] = field(
129
+ default=5,
130
+ metadata={
131
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
132
+ },
133
+ )
134
+ max_seq_length: Optional[int] = field(
135
+ default=None,
136
+ metadata={
137
+ "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."
138
+ },
139
+ )
140
+ preprocessing_num_workers: Optional[int] = field(
141
+ default=None,
142
+ metadata={"help": "The number of processes to use for the preprocessing."},
143
+ )
144
+ mlm_probability: float = field(
145
+ default=0.15, metadata={"help": "Ratio of tokens to mask for span masked language modeling loss"}
146
+ )
147
+ mean_noise_span_length: float = field(
148
+ default=3.0,
149
+ metadata={"help": "Mean span length of masked tokens"},
150
+ )
151
+
152
+ def __post_init__(self):
153
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
154
+ raise ValueError("Need either a dataset name or a training/validation file.")
155
+ else:
156
+ if self.train_file is not None:
157
+ extension = self.train_file.split(".")[-1]
158
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
159
+ if self.validation_file is not None:
160
+ extension = self.validation_file.split(".")[-1]
161
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
162
+
163
+
164
+ def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):
165
+ """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>`__ .
166
+
167
+ Training parameters to avoid padding with random_spans_noise_mask.
168
+ When training a model with random_spans_noise_mask, we would like to set the other
169
+ training hyperparmeters in a way that avoids padding.
170
+ This function helps us compute these hyperparameters.
171
+ We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
172
+ and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
173
+ This function tells us the required number of tokens in the raw example (for split_tokens())
174
+ as well as the length of the encoded targets. Note that this function assumes
175
+ the inputs and targets will have EOS appended and includes that in the reported length.
176
+
177
+ Args:
178
+ inputs_length: an integer - desired length of the tokenized inputs sequence
179
+ noise_density: a float
180
+ mean_noise_span_length: a float
181
+ Returns:
182
+ tokens_length: length of original text in tokens
183
+ targets_length: an integer - length in tokens of encoded targets sequence
184
+ """
185
+
186
+ def _tokens_length_to_inputs_length_targets_length(tokens_length):
187
+ num_noise_tokens = int(round(tokens_length * noise_density))
188
+ num_nonnoise_tokens = tokens_length - num_noise_tokens
189
+ num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
190
+ # inputs contain all nonnoise tokens, sentinels for all noise spans
191
+ # and one EOS token.
192
+ _input_length = num_nonnoise_tokens + num_noise_spans + 1
193
+ _output_length = num_noise_tokens + num_noise_spans + 1
194
+ return _input_length, _output_length
195
+
196
+ tokens_length = inputs_length
197
+
198
+ while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
199
+ tokens_length += 1
200
+
201
+ inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
202
+
203
+ # minor hack to get the targets length to be equal to inputs length
204
+ # which is more likely to have been set to a nice round number.
205
+ if noise_density == 0.5 and targets_length > inputs_length:
206
+ tokens_length -= 1
207
+ targets_length -= 1
208
+ return tokens_length, targets_length
209
+
210
+
211
+ @flax.struct.dataclass
212
+ class FlaxDataCollatorForT5MLM:
213
+ """
214
+ Data collator used for T5 span-masked language modeling.
215
+ It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
216
+ For more information on how T5 span-masked language modeling works, one can take a look
217
+ at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
218
+ or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
219
+
220
+ Args:
221
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
222
+ The tokenizer used for encoding the data.
223
+ noise_density (:obj:`float`):
224
+ The probability with which to (randomly) mask tokens in the input.
225
+ mean_noise_span_length (:obj:`float`):
226
+ The average span length of the masked tokens.
227
+ input_length (:obj:`int`):
228
+ The expected input length after masking.
229
+ target_length (:obj:`int`):
230
+ The expected target length after masking.
231
+ pad_token_id: (:obj:`int`):
232
+ The pad token id of the model
233
+ decoder_start_token_id: (:obj:`int):
234
+ The decoder start token id of the model
235
+ """
236
+
237
+ tokenizer: PreTrainedTokenizerBase
238
+ noise_density: float
239
+ mean_noise_span_length: float
240
+ input_length: int
241
+ target_length: int
242
+ pad_token_id: int
243
+ decoder_start_token_id: int
244
+
245
+ def __call__(self, examples: List[Dict[str, np.ndarray]]) -> Dict[str, np.ndarray]:
246
+
247
+ # convert list to dict and tensorize input
248
+ batch = BatchEncoding(
249
+ {k: np.array([examples[i][k] for i in range(len(examples))]) for k, v in examples[0].items()}
250
+ )
251
+
252
+ input_ids = batch["input_ids"]
253
+ batch_size, expandend_input_length = input_ids.shape
254
+
255
+ mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
256
+ labels_mask = ~mask_indices
257
+
258
+ input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
259
+ labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
260
+
261
+ batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
262
+ batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
263
+
264
+ if batch["input_ids"].shape[-1] != self.input_length:
265
+ raise ValueError(
266
+ f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but should be {self.target_length}."
267
+ )
268
+
269
+ if batch["labels"].shape[-1] != self.target_length:
270
+ raise ValueError(
271
+ f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be {self.target_length}."
272
+ )
273
+
274
+ # to check that tokens are correctly proprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
275
+ batch["decoder_input_ids"] = shift_tokens_right(
276
+ batch["labels"], self.pad_token_id, self.decoder_start_token_id
277
+ )
278
+
279
+ return batch
280
+
281
+ def create_sentinel_ids(self, mask_indices):
282
+ """
283
+ Sentinel ids creation given the indices that should be masked.
284
+ The start indices of each mask are replaced by the sentinel ids in increasing
285
+ order. Consecutive mask indices to be deleted are replaced with `-1`.
286
+ """
287
+ start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
288
+ start_indices[:, 0] = mask_indices[:, 0]
289
+
290
+ sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
291
+ sentinel_ids = np.where(sentinel_ids != 0, (sentinel_ids + self.tokenizer.vocab_size - 1), 0)
292
+ sentinel_ids -= mask_indices - start_indices
293
+
294
+ return sentinel_ids
295
+
296
+ def filter_input_ids(self, input_ids, sentinel_ids):
297
+ """
298
+ Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
299
+ This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
300
+ """
301
+ batch_size = input_ids.shape[0]
302
+
303
+ input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
304
+ input_ids = input_ids_full[input_ids_full > 0].reshape((batch_size, -1))
305
+ input_ids = np.concatenate(
306
+ [input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
307
+ )
308
+ return input_ids
309
+
310
+ def random_spans_noise_mask(self, length):
311
+
312
+ """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>`__ .
313
+
314
+ Noise mask consisting of random spans of noise tokens.
315
+ The number of noise tokens and the number of noise spans and non-noise spans
316
+ are determined deterministically as follows:
317
+ num_noise_tokens = round(length * noise_density)
318
+ num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
319
+ Spans alternate between non-noise and noise, beginning with non-noise.
320
+ Subject to the above restrictions, all masks are equally likely.
321
+
322
+ Args:
323
+ length: an int32 scalar (length of the incoming token sequence)
324
+ noise_density: a float - approximate density of output mask
325
+ mean_noise_span_length: a number
326
+
327
+ Returns:
328
+ a boolean tensor with shape [length]
329
+ """
330
+
331
+ orig_length = length
332
+
333
+ num_noise_tokens = int(np.round(length * self.noise_density))
334
+ # avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
335
+ num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
336
+ num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
337
+
338
+ # avoid degeneracy by ensuring positive number of noise spans
339
+ num_noise_spans = max(num_noise_spans, 1)
340
+ num_nonnoise_tokens = length - num_noise_tokens
341
+
342
+ # pick the lengths of the noise spans and the non-noise spans
343
+ def _random_segmentation(num_items, num_segments):
344
+ """Partition a sequence of items randomly into non-empty segments.
345
+ Args:
346
+ num_items: an integer scalar > 0
347
+ num_segments: an integer scalar in [1, num_items]
348
+ Returns:
349
+ a Tensor with shape [num_segments] containing positive integers that add
350
+ up to num_items
351
+ """
352
+ mask_indices = np.arange(num_items - 1) < (num_segments - 1)
353
+ np.random.shuffle(mask_indices)
354
+ first_in_segment = np.pad(mask_indices, [[1, 0]])
355
+ segment_id = np.cumsum(first_in_segment)
356
+ segment_length = np.asarray(jax.ops.segment_sum(np.ones_like(segment_id), segment_id))
357
+ return segment_length
358
+
359
+ noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
360
+ nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
361
+
362
+ interleaved_span_lengths = np.reshape(
363
+ np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
364
+ )
365
+ span_starts = np.cumsum(interleaved_span_lengths)[:-1]
366
+ span_start_indicator = np.zeros((length,), dtype=np.int8)
367
+ span_start_indicator[span_starts] = True
368
+ span_num = np.cumsum(span_start_indicator)
369
+ is_noise = np.equal(span_num % 2, 1)
370
+
371
+ return is_noise[:orig_length]
372
+
373
+
374
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
375
+ num_samples = len(samples_idx)
376
+ samples_to_remove = num_samples % batch_size
377
+
378
+ if samples_to_remove != 0:
379
+ samples_idx = samples_idx[:-samples_to_remove]
380
+ sections_split = num_samples // batch_size
381
+ batch_idx = np.split(samples_idx, sections_split)
382
+ return batch_idx
383
+
384
+
385
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
386
+ summary_writer.scalar("train_time", train_time, step)
387
+
388
+ train_metrics = get_metrics(train_metrics)
389
+ for key, vals in train_metrics.items():
390
+ tag = f"train_{key}"
391
+ for i, val in enumerate(vals):
392
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
393
+
394
+
395
+ def write_eval_metric(summary_writer, eval_metrics, step):
396
+ for metric_name, value in eval_metrics.items():
397
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
398
+
399
+
400
+ if __name__ == "__main__":
401
+ # See all possible arguments in src/transformers/training_args.py
402
+ # or by passing the --help flag to this script.
403
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
404
+
405
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
406
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
407
+ # If we pass only one argument to the script and it's the path to a json file,
408
+ # let's parse it to get our arguments.
409
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
410
+ else:
411
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
412
+
413
+ if (
414
+ os.path.exists(training_args.output_dir)
415
+ and os.listdir(training_args.output_dir)
416
+ and training_args.do_train
417
+ and not training_args.overwrite_output_dir
418
+ ):
419
+ raise ValueError(
420
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
421
+ "Use --overwrite_output_dir to overcome."
422
+ )
423
+
424
+ # Setup logging
425
+ logging.basicConfig(
426
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
427
+ level="NOTSET",
428
+ datefmt="[%X]",
429
+ )
430
+
431
+ # Log on each process the small summary:
432
+ logger = logging.getLogger(__name__)
433
+
434
+ # Set the verbosity to info of the Transformers logger (on main process only):
435
+ logger.info(f"Training/evaluation parameters {training_args}")
436
+
437
+ # Set seed before initializing model.
438
+ set_seed(training_args.seed)
439
+
440
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
441
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
442
+ # (the dataset will be downloaded automatically from the datasets Hub).
443
+ #
444
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
445
+ # 'text' is found. You can easily tweak this behavior (see below).
446
+ if data_args.dataset_name is not None:
447
+ # Downloading and loading a dataset from the hub.
448
+ datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir)
449
+
450
+ if "validation" not in datasets.keys():
451
+ datasets["validation"] = load_dataset(
452
+ data_args.dataset_name,
453
+ data_args.dataset_config_name,
454
+ split=f"train[:{data_args.validation_split_percentage}%]",
455
+ cache_dir=model_args.cache_dir,
456
+ )
457
+ datasets["train"] = load_dataset(
458
+ data_args.dataset_name,
459
+ data_args.dataset_config_name,
460
+ split=f"train[{data_args.validation_split_percentage}%:]",
461
+ cache_dir=model_args.cache_dir,
462
+ )
463
+ else:
464
+ data_files = {}
465
+ if data_args.train_file is not None:
466
+ data_files["train"] = data_args.train_file
467
+ if data_args.validation_file is not None:
468
+ data_files["validation"] = data_args.validation_file
469
+ extension = data_args.train_file.split(".")[-1]
470
+ if extension == "txt":
471
+ extension = "text"
472
+ datasets = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
473
+
474
+ if "validation" not in datasets.keys():
475
+ datasets["validation"] = load_dataset(
476
+ extension,
477
+ data_files=data_files,
478
+ split=f"train[:{data_args.validation_split_percentage}%]",
479
+ cache_dir=model_args.cache_dir,
480
+ )
481
+ datasets["train"] = load_dataset(
482
+ extension,
483
+ data_files=data_files,
484
+ split=f"train[{data_args.validation_split_percentage}%:]",
485
+ cache_dir=model_args.cache_dir,
486
+ )
487
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
488
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
489
+
490
+ # Load pretrained model and tokenizer
491
+
492
+ if model_args.tokenizer_name:
493
+ tokenizer = AutoTokenizer.from_pretrained(
494
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
495
+ )
496
+ elif model_args.model_name_or_path:
497
+ tokenizer = AutoTokenizer.from_pretrained(
498
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
499
+ )
500
+ else:
501
+ raise ValueError(
502
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
503
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
504
+ )
505
+
506
+ if model_args.config_name:
507
+ config = T5Config.from_pretrained(
508
+ model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
509
+ )
510
+ elif model_args.model_name_or_path:
511
+ config = T5Config.from_pretrained(
512
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
513
+ )
514
+ else:
515
+ config = CONFIG_MAPPING[model_args.model_type]()
516
+ logger.warning("You are instantiating a new config instance from scratch.")
517
+
518
+ # Preprocessing the datasets.
519
+ # First we tokenize all the texts.
520
+ if training_args.do_train:
521
+ column_names = datasets["train"].column_names
522
+ else:
523
+ column_names = datasets["validation"].column_names
524
+ text_column_name = "text" if "text" in column_names else column_names[0]
525
+
526
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
527
+
528
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
529
+ # Since we make sure that all sequences are of the same length, no attention_mask is needed.
530
+ def tokenize_function(examples):
531
+ return tokenizer(examples[text_column_name], return_attention_mask=False)
532
+
533
+ tokenized_datasets = datasets.map(
534
+ tokenize_function,
535
+ batched=True,
536
+ num_proc=data_args.preprocessing_num_workers,
537
+ remove_columns=column_names,
538
+ load_from_cache_file=not data_args.overwrite_cache,
539
+ )
540
+
541
+ # T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
542
+ # To ensure that the input length is `max_seq_length`, we need to increase the maximum length
543
+ # according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
544
+ expanded_inputs_length, targets_length = compute_input_and_target_lengths(
545
+ inputs_length=max_seq_length,
546
+ noise_density=data_args.mlm_probability,
547
+ mean_noise_span_length=data_args.mean_noise_span_length,
548
+ )
549
+
550
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length.
551
+ def group_texts(examples):
552
+ # Concatenate all texts.
553
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
554
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
555
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
556
+ # customize this part to your needs.
557
+ if total_length >= expanded_inputs_length:
558
+ total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
559
+ # Split by chunks of max_len.
560
+ result = {
561
+ k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
562
+ for k, t in concatenated_examples.items()
563
+ }
564
+ return result
565
+
566
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
567
+ # remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
568
+ # might be slower to preprocess.
569
+ #
570
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
571
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
572
+ tokenized_datasets = tokenized_datasets.map(
573
+ group_texts,
574
+ batched=True,
575
+ num_proc=data_args.preprocessing_num_workers,
576
+ load_from_cache_file=not data_args.overwrite_cache,
577
+ )
578
+
579
+ # Enable tensorboard only on the master node
580
+ has_tensorboard = is_tensorboard_available()
581
+ if has_tensorboard and jax.process_index() == 0:
582
+ try:
583
+ from flax.metrics.tensorboard import SummaryWriter
584
+
585
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
586
+ except ImportError as ie:
587
+ has_tensorboard = False
588
+ logger.warning(
589
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
590
+ )
591
+ else:
592
+ logger.warning(
593
+ "Unable to display metrics through TensorBoard because the package is not installed: "
594
+ "Please run pip install tensorboard to enable."
595
+ )
596
+
597
+ # Initialize our training
598
+ rng = jax.random.PRNGKey(training_args.seed)
599
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
600
+
601
+ if model_args.model_name_or_path:
602
+ model = FlaxT5ForConditionalGeneration.from_pretrained(
603
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
604
+ )
605
+ else:
606
+ model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
607
+
608
+ # Data collator
609
+ # This one will take care of randomly masking the tokens.
610
+ data_collator = FlaxDataCollatorForT5MLM(
611
+ tokenizer=tokenizer,
612
+ noise_density=data_args.mlm_probability,
613
+ mean_noise_span_length=data_args.mean_noise_span_length,
614
+ input_length=max_seq_length,
615
+ target_length=targets_length,
616
+ pad_token_id=model.config.pad_token_id,
617
+ decoder_start_token_id=model.config.decoder_start_token_id,
618
+ )
619
+
620
+ # Store some constant
621
+ num_epochs = int(training_args.num_train_epochs)
622
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
623
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
624
+
625
+ num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
626
+
627
+ # Create learning rate schedule
628
+ warmup_fn = optax.linear_schedule(
629
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
630
+ )
631
+ decay_fn = optax.linear_schedule(
632
+ init_value=training_args.learning_rate,
633
+ end_value=0,
634
+ transition_steps=num_train_steps - training_args.warmup_steps,
635
+ )
636
+ linear_decay_lr_schedule_fn = optax.join_schedules(
637
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
638
+ )
639
+
640
+ # We use Optax's "masking" functionality to not apply weight decay
641
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
642
+ # mask boolean with the same structure as the parameters.
643
+ # The mask is True for parameters that should be decayed.
644
+ def decay_mask_fn(params):
645
+ flat_params = traverse_util.flatten_dict(params)
646
+ flat_mask = {
647
+ path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
648
+ for path in flat_params
649
+ }
650
+ return traverse_util.unflatten_dict(flat_mask)
651
+
652
+ # create adam optimizer
653
+ if training_args.adafactor:
654
+ # We use the default parameters here to initialize adafactor,
655
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
656
+ optimizer = optax.adafactor(
657
+ learning_rate=linear_decay_lr_schedule_fn,
658
+ )
659
+ else:
660
+ optimizer = optax.adamw(
661
+ learning_rate=linear_decay_lr_schedule_fn,
662
+ b1=training_args.adam_beta1,
663
+ b2=training_args.adam_beta2,
664
+ weight_decay=training_args.weight_decay,
665
+ mask=decay_mask_fn,
666
+ )
667
+
668
+ # Setup train state
669
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
670
+
671
+ # Define gradient update step fn
672
+ def train_step(state, batch, dropout_rng):
673
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
674
+
675
+ def loss_fn(params):
676
+ labels = batch.pop("labels")
677
+
678
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
679
+
680
+ # compute loss
681
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
682
+
683
+ return loss
684
+
685
+ grad_fn = jax.value_and_grad(loss_fn)
686
+ loss, grad = grad_fn(state.params)
687
+ grad = jax.lax.pmean(grad, "batch")
688
+ new_state = state.apply_gradients(grads=grad)
689
+
690
+ metrics = jax.lax.pmean(
691
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
692
+ )
693
+
694
+ return new_state, metrics, new_dropout_rng
695
+
696
+ # Create parallel version of the train step
697
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
698
+
699
+ # Define eval fn
700
+ def eval_step(params, batch):
701
+ labels = batch.pop("labels")
702
+
703
+ logits = model(**batch, params=params, train=False)[0]
704
+
705
+ # compute loss
706
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
707
+
708
+ # compute accuracy
709
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
710
+
711
+ # summarize metrics
712
+ metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
713
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
714
+
715
+ return metrics
716
+
717
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
718
+
719
+ # Replicate the train state on each device
720
+ state = jax_utils.replicate(state)
721
+
722
+ train_time = 0
723
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
724
+ for epoch in epochs:
725
+ # ======================== Training ================================
726
+ train_start = time.time()
727
+ train_metrics = []
728
+
729
+ # Create sampling rng
730
+ rng, input_rng = jax.random.split(rng)
731
+
732
+ # Generate an epoch by shuffling sampling indices from the train dataset
733
+ num_train_samples = len(tokenized_datasets["train"])
734
+ train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
735
+ train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
736
+
737
+ # Gather the indexes for creating the batch and do a training step
738
+ for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
739
+ samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
740
+ model_inputs = data_collator(samples)
741
+
742
+ # Model forward
743
+ model_inputs = shard(model_inputs.data)
744
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
745
+ train_metrics.append(train_metric)
746
+
747
+ cur_step = epoch * (num_train_samples // train_batch_size) + step
748
+
749
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
750
+ # Save metrics
751
+ train_metric = jax_utils.unreplicate(train_metric)
752
+ train_time += time.time() - train_start
753
+ if has_tensorboard and jax.process_index() == 0:
754
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
755
+
756
+ epochs.write(
757
+ f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
758
+ )
759
+
760
+ train_metrics = []
761
+
762
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
763
+ # ======================== Evaluating ==============================
764
+ num_eval_samples = len(tokenized_datasets["validation"])
765
+ eval_samples_idx = jnp.arange(num_eval_samples)
766
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
767
+
768
+ eval_metrics = []
769
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
770
+ samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
771
+ model_inputs = data_collator(samples)
772
+
773
+ # Model forward
774
+ model_inputs = shard(model_inputs.data)
775
+ metrics = p_eval_step(state.params, model_inputs)
776
+ eval_metrics.append(metrics)
777
+
778
+ # get eval metrics
779
+ eval_metrics = get_metrics(eval_metrics)
780
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
781
+
782
+ # Update progress bar
783
+ epochs.write(f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})")
784
+
785
+ # Save metrics
786
+ if has_tensorboard and jax.process_index() == 0:
787
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
788
+
789
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
790
+ # save checkpoint after each epoch and push checkpoint to the hub
791
+ if jax.process_index() == 0:
792
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
793
+ model.save_pretrained(
794
+ training_args.output_dir,
795
+ params=params,
796
+ push_to_hub=training_args.push_to_hub,
797
+ commit_message=f"Saving weights and logs of step {cur_step}",
798
+ )
run_t5_mlm_flax_streaming.py ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 with T5-like span-masked language modeling on a streaming dataset.
18
+ Here is the full list of checkpoints on the hub that can be pretrained by this script:
19
+ https://huggingface.co/models?filter=t5
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
+ from pathlib import Path
28
+ from typing import Dict, Optional
29
+
30
+ import datasets
31
+ import numpy as np
32
+ from datasets import load_dataset
33
+ from tqdm import tqdm
34
+
35
+ import flax
36
+ import jax
37
+ import jax.numpy as jnp
38
+ import optax
39
+ from flax import jax_utils, traverse_util
40
+ from flax.training import train_state
41
+ from flax.training.common_utils import get_metrics, onehot, shard
42
+ from transformers import (
43
+ CONFIG_MAPPING,
44
+ FLAX_MODEL_FOR_MASKED_LM_MAPPING,
45
+ BatchEncoding,
46
+ FlaxT5ForConditionalGeneration,
47
+ HfArgumentParser,
48
+ PreTrainedTokenizerBase,
49
+ T5Config,
50
+ T5TokenizerFast,
51
+ TrainingArguments,
52
+ is_tensorboard_available,
53
+ set_seed,
54
+ )
55
+ from transformers.models.t5.modeling_flax_t5 import shift_tokens_right
56
+
57
+ #if datasets.__version__ <= "1.8.0":
58
+ # raise ValueError("Make sure to upgrade `datasets` to a version >= 1.9.0 to use dataset streaming")
59
+
60
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_MASKED_LM_MAPPING.keys())
61
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
62
+
63
+
64
+ @dataclass
65
+ class ModelArguments:
66
+ """
67
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
68
+ """
69
+
70
+ model_name_or_path: Optional[str] = field(
71
+ default=None,
72
+ metadata={
73
+ "help": "The model checkpoint for weights initialization."
74
+ "Don't set if you want to train a model from scratch."
75
+ },
76
+ )
77
+ model_type: Optional[str] = field(
78
+ default=None,
79
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
80
+ )
81
+ config_name: Optional[str] = field(
82
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
83
+ )
84
+ tokenizer_name: Optional[str] = field(
85
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
86
+ )
87
+ cache_dir: Optional[str] = field(
88
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
89
+ )
90
+ use_fast_tokenizer: bool = field(
91
+ default=True,
92
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
93
+ )
94
+ dtype: Optional[str] = field(
95
+ default="float32",
96
+ metadata={
97
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
98
+ },
99
+ )
100
+ auth_token: Optional[str] = field(
101
+ default=None,
102
+ metadata={
103
+ "help": "Auth token for private repositories on the Huggingface Hub"
104
+ }
105
+ )
106
+
107
+
108
+ @dataclass
109
+ class DataTrainingArguments:
110
+ """
111
+ Arguments pertaining to what data we are going to input our model for training and eval.
112
+ """
113
+
114
+ dataset_name: Optional[str] = field(
115
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
116
+ )
117
+ dataset_config_name: Optional[str] = field(
118
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
119
+ )
120
+ max_seq_length: Optional[int] = field(
121
+ default=None,
122
+ metadata={
123
+ "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."
124
+ },
125
+ )
126
+ preprocessing_num_workers: Optional[int] = field(
127
+ default=None,
128
+ metadata={"help": "The number of processes to use for the preprocessing."},
129
+ )
130
+ mlm_probability: float = field(
131
+ default=0.15, metadata={"help": "Ratio of tokens to mask for span masked language modeling loss"}
132
+ )
133
+ mean_noise_span_length: float = field(
134
+ default=3.0,
135
+ metadata={"help": "Mean span length of masked tokens"},
136
+ )
137
+ text_column_name: str = field(
138
+ default="text", metadata={"help": "The name of the column to retrieve the training text."}
139
+ )
140
+ shuffle_buffer_size: int = field(
141
+ default=10000, metadata={"help": "The number of examples to pre-load for shuffling."}
142
+ )
143
+ num_train_steps: int = field(default=50000, metadata={"help": "The number of training steps."})
144
+ num_eval_samples: int = field(default=50000, metadata={"help": "The number of samples to be used for evaluation"})
145
+
146
+ def __post_init__(self):
147
+ if self.dataset_name is None:
148
+ raise ValueError("Need a dataset name for streaming.")
149
+
150
+
151
+ def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):
152
+ """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>`__ .
153
+ Training parameters to avoid padding with random_spans_noise_mask.
154
+ When training a model with random_spans_noise_mask, we would like to set the other
155
+ training hyperparmeters in a way that avoids padding.
156
+ This function helps us compute these hyperparameters.
157
+ We assume that each noise span in the input is replaced by extra_tokens_per_span_inputs sentinel tokens,
158
+ and each non-noise span in the targets is replaced by extra_tokens_per_span_targets sentinel tokens.
159
+ This function tells us the required number of tokens in the raw example (for split_tokens())
160
+ as well as the length of the encoded targets. Note that this function assumes
161
+ the inputs and targets will have EOS appended and includes that in the reported length.
162
+ Args:
163
+ inputs_length: an integer - desired length of the tokenized inputs sequence
164
+ noise_density: a float
165
+ mean_noise_span_length: a float
166
+ Returns:
167
+ tokens_length: length of original text in tokens
168
+ targets_length: an integer - length in tokens of encoded targets sequence
169
+ """
170
+
171
+ def _tokens_length_to_inputs_length_targets_length(tokens_length):
172
+ num_noise_tokens = int(round(tokens_length * noise_density))
173
+ num_nonnoise_tokens = tokens_length - num_noise_tokens
174
+ num_noise_spans = int(round(num_noise_tokens / mean_noise_span_length))
175
+ # inputs contain all nonnoise tokens, sentinels for all noise spans
176
+ # and one EOS token.
177
+ _input_length = num_nonnoise_tokens + num_noise_spans + 1
178
+ _output_length = num_noise_tokens + num_noise_spans + 1
179
+ return _input_length, _output_length
180
+
181
+ tokens_length = inputs_length
182
+
183
+ while _tokens_length_to_inputs_length_targets_length(tokens_length + 1)[0] <= inputs_length:
184
+ tokens_length += 1
185
+
186
+ inputs_length, targets_length = _tokens_length_to_inputs_length_targets_length(tokens_length)
187
+
188
+ # minor hack to get the targets length to be equal to inputs length
189
+ # which is more likely to have been set to a nice round number.
190
+ if noise_density == 0.5 and targets_length > inputs_length:
191
+ tokens_length -= 1
192
+ targets_length -= 1
193
+ return tokens_length, targets_length
194
+
195
+
196
+ @flax.struct.dataclass
197
+ class FlaxDataCollatorForT5MLM:
198
+ """
199
+ Data collator used for T5 span-masked language modeling.
200
+ It is made sure that after masking the inputs are of length `data_args.max_seq_length` and targets are also of fixed length.
201
+ For more information on how T5 span-masked language modeling works, one can take a look
202
+ at the `official paper <https://arxiv.org/pdf/1910.10683.pdf>`__
203
+ or the `official code for preprocessing <https://github.com/google-research/text-to-text-transfer-transformer/blob/master/t5/data/preprocessors.py>`__ .
204
+ Args:
205
+ tokenizer (:class:`~transformers.PreTrainedTokenizer` or :class:`~transformers.PreTrainedTokenizerFast`):
206
+ The tokenizer used for encoding the data.
207
+ noise_density (:obj:`float`):
208
+ The probability with which to (randomly) mask tokens in the input.
209
+ mean_noise_span_length (:obj:`float`):
210
+ The average span length of the masked tokens.
211
+ input_length (:obj:`int`):
212
+ The expected input length after masking.
213
+ target_length (:obj:`int`):
214
+ The expected target length after masking.
215
+ pad_token_id: (:obj:`int`):
216
+ The pad token id of the model
217
+ decoder_start_token_id: (:obj:`int):
218
+ The decoder start token id of the model
219
+ """
220
+
221
+ tokenizer: PreTrainedTokenizerBase
222
+ noise_density: float
223
+ mean_noise_span_length: float
224
+ input_length: int
225
+ target_length: int
226
+ pad_token_id: int
227
+ decoder_start_token_id: int
228
+
229
+ def __call__(self, examples: Dict[str, np.ndarray]) -> BatchEncoding:
230
+
231
+ batch = BatchEncoding(
232
+ {k: np.array(examples[k]) for k in examples.keys()}
233
+ )
234
+ input_ids = batch['input_ids']
235
+ batch_size, expandend_input_length = input_ids.shape
236
+
237
+ mask_indices = np.asarray([self.random_spans_noise_mask(expandend_input_length) for i in range(batch_size)])
238
+ labels_mask = ~mask_indices
239
+
240
+ input_ids_sentinel = self.create_sentinel_ids(mask_indices.astype(np.int8))
241
+ labels_sentinel = self.create_sentinel_ids(labels_mask.astype(np.int8))
242
+
243
+ batch["input_ids"] = self.filter_input_ids(input_ids, input_ids_sentinel)
244
+ batch["labels"] = self.filter_input_ids(input_ids, labels_sentinel)
245
+
246
+ if batch["input_ids"].shape[-1] != self.input_length:
247
+ raise ValueError(
248
+ f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but should be {self.target_length}."
249
+ )
250
+
251
+ if batch["labels"].shape[-1] != self.target_length:
252
+ raise ValueError(
253
+ f"`labels` are incorrectly preprocessed. `labels` length is {batch['labels'].shape[-1]}, but should be {self.target_length}."
254
+ )
255
+
256
+ # to check that tokens are correctly proprocessed, one can run `self.tokenizer.batch_decode(input_ids)` and `self.tokenizer.batch_decode(labels)` here...
257
+ batch["decoder_input_ids"] = shift_tokens_right(
258
+ batch["labels"], self.pad_token_id, self.decoder_start_token_id
259
+ )
260
+
261
+ return batch
262
+
263
+ def create_sentinel_ids(self, mask_indices):
264
+ """
265
+ Sentinel ids creation given the indices that should be masked.
266
+ The start indices of each mask are replaced by the sentinel ids in increasing
267
+ order. Consecutive mask indices to be deleted are replaced with `-1`.
268
+ """
269
+ start_indices = mask_indices - np.roll(mask_indices, 1, axis=-1) * mask_indices
270
+ start_indices[:, 0] = mask_indices[:, 0]
271
+
272
+ sentinel_ids = np.where(start_indices != 0, np.cumsum(start_indices, axis=-1), start_indices)
273
+ sentinel_ids = np.where(sentinel_ids != 0, (sentinel_ids + self.tokenizer.vocab_size - 1), 0)
274
+ sentinel_ids -= mask_indices - start_indices
275
+
276
+ return sentinel_ids
277
+
278
+ def filter_input_ids(self, input_ids, sentinel_ids):
279
+ """
280
+ Puts sentinel mask on `input_ids` and fuse consecutive mask tokens into a single mask token by deleting.
281
+ This will reduce the sequence length from `expanded_inputs_length` to `input_length`.
282
+ """
283
+ batch_size = input_ids.shape[0]
284
+
285
+ input_ids_full = np.where(sentinel_ids != 0, sentinel_ids, input_ids)
286
+ input_ids = input_ids_full[input_ids_full > 0].reshape((batch_size, -1))
287
+ input_ids = np.concatenate(
288
+ [input_ids, np.full((batch_size, 1), self.tokenizer.eos_token_id, dtype=np.int32)], axis=-1
289
+ )
290
+ return input_ids
291
+
292
+ def random_spans_noise_mask(self, length):
293
+
294
+ """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>`__ .
295
+ Noise mask consisting of random spans of noise tokens.
296
+ The number of noise tokens and the number of noise spans and non-noise spans
297
+ are determined deterministically as follows:
298
+ num_noise_tokens = round(length * noise_density)
299
+ num_nonnoise_spans = num_noise_spans = round(num_noise_tokens / mean_noise_span_length)
300
+ Spans alternate between non-noise and noise, beginning with non-noise.
301
+ Subject to the above restrictions, all masks are equally likely.
302
+ Args:
303
+ length: an int32 scalar (length of the incoming token sequence)
304
+ noise_density: a float - approximate density of output mask
305
+ mean_noise_span_length: a number
306
+ Returns:
307
+ a boolean tensor with shape [length]
308
+ """
309
+
310
+ orig_length = length
311
+
312
+ num_noise_tokens = int(np.round(length * self.noise_density))
313
+ # avoid degeneracy by ensuring positive numbers of noise and nonnoise tokens.
314
+ num_noise_tokens = min(max(num_noise_tokens, 1), length - 1)
315
+ num_noise_spans = int(np.round(num_noise_tokens / self.mean_noise_span_length))
316
+
317
+ # avoid degeneracy by ensuring positive number of noise spans
318
+ num_noise_spans = max(num_noise_spans, 1)
319
+ num_nonnoise_tokens = length - num_noise_tokens
320
+
321
+ # pick the lengths of the noise spans and the non-noise spans
322
+ def _random_segmentation(num_items, num_segments):
323
+ """Partition a sequence of items randomly into non-empty segments.
324
+ Args:
325
+ num_items: an integer scalar > 0
326
+ num_segments: an integer scalar in [1, num_items]
327
+ Returns:
328
+ a Tensor with shape [num_segments] containing positive integers that add
329
+ up to num_items
330
+ """
331
+ mask_indices = np.arange(num_items - 1) < (num_segments - 1)
332
+ np.random.shuffle(mask_indices)
333
+ first_in_segment = np.pad(mask_indices, [[1, 0]])
334
+ segment_id = np.cumsum(first_in_segment)
335
+ # count length of sub segments assuming that list is sorted
336
+ _, segment_length = np.unique(segment_id, return_counts=True)
337
+ return segment_length
338
+
339
+ noise_span_lengths = _random_segmentation(num_noise_tokens, num_noise_spans)
340
+ nonnoise_span_lengths = _random_segmentation(num_nonnoise_tokens, num_noise_spans)
341
+
342
+ interleaved_span_lengths = np.reshape(
343
+ np.stack([nonnoise_span_lengths, noise_span_lengths], axis=1), [num_noise_spans * 2]
344
+ )
345
+ span_starts = np.cumsum(interleaved_span_lengths)[:-1]
346
+ span_start_indicator = np.zeros((length,), dtype=np.int8)
347
+ span_start_indicator[span_starts] = True
348
+ span_num = np.cumsum(span_start_indicator)
349
+ is_noise = np.equal(span_num % 2, 1)
350
+
351
+ return is_noise[:orig_length]
352
+
353
+
354
+ def generate_batch_splits(samples_idx: jnp.ndarray, batch_size: int) -> jnp.ndarray:
355
+ num_samples = len(samples_idx)
356
+ samples_to_remove = num_samples % batch_size
357
+
358
+ if samples_to_remove != 0:
359
+ samples_idx = samples_idx[:-samples_to_remove]
360
+ sections_split = num_samples // batch_size
361
+ batch_idx = np.split(samples_idx, sections_split)
362
+ return batch_idx
363
+
364
+
365
+ def advance_iter_and_group_samples(train_iterator, num_samples, max_seq_length):
366
+ """
367
+ The training iterator is advanced so that after groupifying the samples,
368
+ `num_samples` of length `max_seq_length` are returned.
369
+ """
370
+ num_total_tokens = max_seq_length * num_samples
371
+ samples = defaultdict(list)
372
+
373
+ i = 0
374
+ while i < num_total_tokens:
375
+ tokenized_samples = next(train_iterator)
376
+ i += len(tokenized_samples["input_ids"])
377
+
378
+ # concatenate tokenized samples to list
379
+ samples = {k: samples[k] + tokenized_samples[k] for k in tokenized_samples.keys()}
380
+
381
+ # Concatenated tokens are split to lists of length `max_seq_length`.
382
+ # Note that remainedr of % max_seq_length are thrown away.
383
+ def group_texts(examples):
384
+ result = {
385
+ k: [t[i : i + max_seq_length] for i in range(0, num_total_tokens, max_seq_length)]
386
+ for k, t in examples.items()
387
+ }
388
+ return result
389
+
390
+ grouped_samples = group_texts(samples)
391
+ return grouped_samples
392
+
393
+
394
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
395
+ summary_writer.scalar("train_time", train_time, step)
396
+
397
+ train_metrics = get_metrics(train_metrics)
398
+ for key, vals in train_metrics.items():
399
+ tag = f"train_{key}"
400
+ for i, val in enumerate(vals):
401
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
402
+
403
+
404
+ def write_eval_metric(summary_writer, eval_metrics, step):
405
+ for metric_name, value in eval_metrics.items():
406
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
407
+
408
+
409
+ if __name__ == "__main__":
410
+ # See all possible arguments in src/transformers/training_args.py
411
+ # or by passing the --help flag to this script.
412
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
413
+
414
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
415
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
416
+ # If we pass only one argument to the script and it's the path to a json file,
417
+ # let's parse it to get our arguments.
418
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
419
+ else:
420
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
421
+
422
+ if (
423
+ os.path.exists(training_args.output_dir)
424
+ and os.listdir(training_args.output_dir)
425
+ and training_args.do_train
426
+ and not training_args.overwrite_output_dir
427
+ ):
428
+ raise ValueError(
429
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
430
+ "Use --overwrite_output_dir to overcome."
431
+ )
432
+
433
+ # Setup logging
434
+ logging.basicConfig(
435
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
436
+ level="INFO",
437
+ datefmt="[%X]",
438
+ )
439
+
440
+ # Log on each process the small summary:
441
+ logger = logging.getLogger(__name__)
442
+ #logger.warning(
443
+ # f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
444
+ # + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
445
+ #)
446
+
447
+ # Set the verbosity to info of the Transformers logger (on main process only):
448
+ logger.info(f"Training/evaluation parameters {training_args}")
449
+
450
+ # Set seed before initializing model.
451
+ set_seed(training_args.seed)
452
+
453
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
454
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
455
+ # (the dataset will be downloaded automatically from the datasets Hub).
456
+ #
457
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
458
+ # 'text' is found. You can easily tweak this behavior (see below).
459
+ if data_args.dataset_name is not None:
460
+ # Downloading and loading a dataset from the hub.
461
+ datasets = load_dataset(
462
+ data_args.dataset_name,
463
+ data_args.dataset_config_name,
464
+ cache_dir=model_args.cache_dir,
465
+ streaming=True,
466
+ split="train",
467
+ use_auth_token=True
468
+
469
+ )
470
+
471
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
472
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
473
+
474
+ # Load pretrained model and tokenizer
475
+
476
+ if model_args.tokenizer_name:
477
+ tokenizer = T5TokenizerFast.from_pretrained(
478
+ model_args.tokenizer_name,
479
+ cache_dir=model_args.cache_dir,
480
+ use_fast=model_args.use_fast_tokenizer,
481
+ use_auth_token=model_args.auth_token
482
+ )
483
+ elif model_args.model_name_or_path:
484
+ tokenizer = T5TokenizerFast.from_pretrained(
485
+ model_args.model_name_or_path,
486
+ cache_dir=model_args.cache_dir,
487
+ use_fast=model_args.use_fast_tokenizer,
488
+ use_auth_token=model_args.auth_token
489
+ )
490
+ else:
491
+ raise ValueError(
492
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
493
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
494
+ )
495
+
496
+ if model_args.config_name:
497
+ config = T5Config.from_pretrained(
498
+ model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
499
+ )
500
+ elif model_args.model_name_or_path:
501
+ config = T5Config.from_pretrained(
502
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
503
+ )
504
+ else:
505
+ config = CONFIG_MAPPING[model_args.model_type]()
506
+ logger.warning("You are instantiating a new config instance from scratch.")
507
+
508
+ # Preprocessing the datasets.
509
+ # First we tokenize all the texts.
510
+
511
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
512
+
513
+ # Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
514
+ # Since we make sure that all sequences are of the same length, no attention_mask is needed.
515
+ def tokenize_function(examples):
516
+ return tokenizer(examples[data_args.text_column_name], return_attention_mask=False)
517
+
518
+ tokenized_datasets = datasets.map(
519
+ tokenize_function,
520
+ batched=True
521
+ )
522
+
523
+ # T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
524
+ # To ensure that the input length is `max_seq_length`, we need to increase the maximum length
525
+ # according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
526
+ expanded_inputs_length, targets_length = compute_input_and_target_lengths(
527
+ inputs_length=max_seq_length,
528
+ noise_density=data_args.mlm_probability,
529
+ mean_noise_span_length=data_args.mean_noise_span_length,
530
+ )
531
+
532
+ shuffle_seed = training_args.seed
533
+ tokenized_datasets = tokenized_datasets.shuffle(buffer_size=data_args.shuffle_buffer_size, seed=shuffle_seed)
534
+
535
+ # Enable tensorboard only on the master node
536
+ has_tensorboard = is_tensorboard_available()
537
+ if has_tensorboard and jax.process_index() == 0:
538
+ try:
539
+ from flax.metrics.tensorboard import SummaryWriter
540
+
541
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
542
+ except ImportError as ie:
543
+ has_tensorboard = False
544
+ logger.warning(
545
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
546
+ )
547
+ else:
548
+ logger.warning(
549
+ "Unable to display metrics through TensorBoard because the package is not installed: "
550
+ "Please run pip install tensorboard to enable."
551
+ )
552
+
553
+ # Initialize our training
554
+ rng = jax.random.PRNGKey(training_args.seed)
555
+ dropout_rngs = jax.random.split(rng, jax.local_device_count())
556
+
557
+ #Pere changed 13 august
558
+ #model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
559
+
560
+ if model_args.model_name_or_path:
561
+ model = FlaxT5ForConditionalGeneration.from_pretrained(
562
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
563
+ )
564
+ else:
565
+ model = FlaxT5ForConditionalGeneration.from_pretrained(
566
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
567
+ )
568
+
569
+
570
+ # Data collator
571
+ # This one will take care of randomly masking the tokens.
572
+ data_collator = FlaxDataCollatorForT5MLM(
573
+ tokenizer=tokenizer,
574
+ noise_density=data_args.mlm_probability,
575
+ mean_noise_span_length=data_args.mean_noise_span_length,
576
+ input_length=max_seq_length,
577
+ target_length=targets_length,
578
+ pad_token_id=model.config.pad_token_id,
579
+ decoder_start_token_id=model.config.decoder_start_token_id,
580
+ )
581
+
582
+ # Store some constant
583
+ num_epochs = int(training_args.num_train_epochs)
584
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
585
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
586
+
587
+ num_train_steps = data_args.num_train_steps
588
+
589
+ # Create learning rate schedule
590
+ warmup_fn = optax.linear_schedule(
591
+ init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
592
+ )
593
+ decay_fn = optax.linear_schedule(
594
+ init_value=training_args.learning_rate,
595
+ end_value=0,
596
+ transition_steps=num_train_steps - training_args.warmup_steps,
597
+ )
598
+ linear_decay_lr_schedule_fn = optax.join_schedules(
599
+ schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
600
+ )
601
+
602
+ # We use Optax's "masking" functionality to not apply weight decay
603
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
604
+ # mask boolean with the same structure as the parameters.
605
+ # The mask is True for parameters that should be decayed.
606
+ def decay_mask_fn(params):
607
+ flat_params = traverse_util.flatten_dict(params)
608
+ flat_mask = {
609
+ path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
610
+ for path in flat_params
611
+ }
612
+ return traverse_util.unflatten_dict(flat_mask)
613
+
614
+ # create adam optimizer
615
+ if training_args.adafactor:
616
+ # We use the default parameters here to initialize adafactor,
617
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
618
+ optimizer = optax.adafactor(
619
+ learning_rate=linear_decay_lr_schedule_fn,
620
+ )
621
+ else:
622
+ optimizer = optax.adamw(
623
+ learning_rate=linear_decay_lr_schedule_fn,
624
+ b1=training_args.adam_beta1,
625
+ b2=training_args.adam_beta2,
626
+ weight_decay=training_args.weight_decay,
627
+ mask=decay_mask_fn,
628
+ )
629
+
630
+ # Setup train state
631
+ state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
632
+
633
+ # Define gradient update step fn
634
+ def train_step(state, batch, dropout_rng):
635
+ dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
636
+
637
+ def loss_fn(params):
638
+ labels = batch.pop("labels")
639
+
640
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
641
+
642
+ # compute loss
643
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
644
+
645
+ return loss
646
+
647
+ grad_fn = jax.value_and_grad(loss_fn)
648
+ loss, grad = grad_fn(state.params)
649
+ grad = jax.lax.pmean(grad, "batch")
650
+ new_state = state.apply_gradients(grads=grad)
651
+
652
+ metrics = jax.lax.pmean(
653
+ {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
654
+ )
655
+
656
+ return new_state, metrics, new_dropout_rng
657
+
658
+ # Create parallel version of the train step
659
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
660
+
661
+ # Define eval fn
662
+ def eval_step(params, batch):
663
+ labels = batch.pop("labels")
664
+
665
+ logits = model(**batch, params=params, train=False)[0]
666
+
667
+ # compute loss
668
+ loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
669
+
670
+ # compute accuracy
671
+ accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
672
+
673
+ # summarize metrics
674
+ metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
675
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
676
+
677
+ return metrics
678
+
679
+ p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
680
+
681
+ # Replicate the train state on each device
682
+ state = jax_utils.replicate(state)
683
+
684
+ train_time = 0
685
+ train_start = time.time()
686
+ train_metrics = []
687
+ eval_metrics = []
688
+
689
+ training_iter = iter(tokenized_datasets)
690
+
691
+ eval_samples = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, expanded_inputs_length)
692
+
693
+ steps = tqdm(range(num_train_steps), desc="Training...", position=0)
694
+ for step in range(num_train_steps):
695
+ # ======================== Training ================================
696
+ try:
697
+ samples = advance_iter_and_group_samples(training_iter, train_batch_size, expanded_inputs_length)
698
+ except StopIteration:
699
+ # Once the end of the dataset stream is reached, the training iterator
700
+ # is reinitialized and reshuffled and a new eval dataset is randomely chosen.
701
+ shuffle_seed += 1
702
+ tokenized_datasets.set_epoch(shuffle_seed)
703
+
704
+ training_iter = iter(tokenized_datasets)
705
+
706
+ eval_dataset = advance_iter_and_group_samples(training_iter, data_args.num_eval_samples, expanded_inputs_length)
707
+ samples = advance_iter_and_group_samples(training_iter, train_batch_size, expanded_inputs_length)
708
+
709
+ # Model forward
710
+ model_inputs = data_collator(samples)
711
+ model_inputs = shard(model_inputs.data)
712
+ state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
713
+ train_metrics.append(train_metric)
714
+
715
+ if step % training_args.logging_steps == 0 and step > 0:
716
+ train_metric = jax_utils.unreplicate(train_metric)
717
+ steps.write(
718
+ f"Step... ({step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
719
+ )
720
+ train_time += time.time() - train_start
721
+ if has_tensorboard and jax.process_index() == 0:
722
+ write_train_metric(summary_writer, train_metrics, train_time, step)
723
+ train_metrics = []
724
+ # ======================== Evaluating ==============================
725
+ if step % training_args.eval_steps == 0 and step > 0:
726
+ eval_samples_idx = jnp.arange(data_args.num_eval_samples)
727
+ eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
728
+
729
+ for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=1)):
730
+ # process input samples
731
+ batch_eval_samples = {k: [v[idx] for idx in batch_idx] for k, v in eval_samples.items()}
732
+ model_inputs = data_collator(batch_eval_samples)
733
+
734
+ # Model forward
735
+ model_inputs = shard(model_inputs.data)
736
+ metrics = p_eval_step(state.params, model_inputs)
737
+ eval_metrics.append(metrics)
738
+
739
+ # normalize eval metrics
740
+ eval_metrics = get_metrics(eval_metrics)
741
+ eval_metrics = jax.tree_map(jnp.sum, eval_metrics)
742
+
743
+ # Update progress bar
744
+ steps.desc = f"Step... ({step + 1}/{num_train_steps} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})"
745
+
746
+ if has_tensorboard and jax.process_index() == 0:
747
+ write_eval_metric(summary_writer, eval_metrics, step)
748
+ eval_metrics = []
749
+
750
+ if step % training_args.save_steps == 0 and step > 0:
751
+ # save checkpoint after each save_steps and push checkpoint to the hub
752
+ if jax.process_index() == 0:
753
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
754
+ model.save_pretrained(
755
+ training_args.output_dir,
756
+ params=params,
757
+ push_to_hub=training_args.push_to_hub,
758
+ commit_message=f"Saving weights and logs of step {step+1}",
759
+ )
760
+ # print(training_args.output_dir)
761
+ # tokenizer.save_pretrained(
762
+ # training_args.output_dir
763
+ # )
764
+
765
+ # update tqdm bar
766
+ steps.update(1)
767
+
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>", "additional_special_tokens": ["<extra_id_0>", "<extra_id_1>", "<extra_id_2>", "<extra_id_3>", "<extra_id_4>", "<extra_id_5>", "<extra_id_6>", "<extra_id_7>", "<extra_id_8>", "<extra_id_9>", "<extra_id_10>", "<extra_id_11>", "<extra_id_12>", "<extra_id_13>", "<extra_id_14>", "<extra_id_15>", "<extra_id_16>", "<extra_id_17>", "<extra_id_18>", "<extra_id_19>", "<extra_id_20>", "<extra_id_21>", "<extra_id_22>", "<extra_id_23>", "<extra_id_24>", "<extra_id_25>", "<extra_id_26>", "<extra_id_27>", "<extra_id_28>", "<extra_id_29>", "<extra_id_30>", "<extra_id_31>", "<extra_id_32>", "<extra_id_33>", "<extra_id_34>", "<extra_id_35>", "<extra_id_36>", "<extra_id_37>", "<extra_id_38>", "<extra_id_39>", "<extra_id_40>", "<extra_id_41>", "<extra_id_42>", "<extra_id_43>", "<extra_id_44>", "<extra_id_45>", "<extra_id_46>", "<extra_id_47>", "<extra_id_48>", "<extra_id_49>", "<extra_id_50>", "<extra_id_51>", "<extra_id_52>", "<extra_id_53>", "<extra_id_54>", "<extra_id_55>", "<extra_id_56>", "<extra_id_57>", "<extra_id_58>", "<extra_id_59>", "<extra_id_60>", "<extra_id_61>", "<extra_id_62>", "<extra_id_63>", "<extra_id_64>", "<extra_id_65>", "<extra_id_66>", "<extra_id_67>", "<extra_id_68>", "<extra_id_69>", "<extra_id_70>", "<extra_id_71>", "<extra_id_72>", "<extra_id_73>", "<extra_id_74>", "<extra_id_75>", "<extra_id_76>", "<extra_id_77>", "<extra_id_78>", "<extra_id_79>", "<extra_id_80>", "<extra_id_81>", "<extra_id_82>", "<extra_id_83>", "<extra_id_84>", "<extra_id_85>", "<extra_id_86>", "<extra_id_87>", "<extra_id_88>", "<extra_id_89>", "<extra_id_90>", "<extra_id_91>", "<extra_id_92>", "<extra_id_93>", "<extra_id_94>", "<extra_id_95>", "<extra_id_96>", "<extra_id_97>", "<extra_id_98>", "<extra_id_99>"]}
t5_tokenizer_model.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import json
3
+ from typing import Iterator, List, Union
4
+
5
+ from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers
6
+ from tokenizers.implementations.base_tokenizer import BaseTokenizer
7
+ from tokenizers.models import Unigram
8
+ from tokenizers.processors import TemplateProcessing
9
+
10
+
11
+ class SentencePieceUnigramTokenizer(BaseTokenizer):
12
+ """
13
+ This class is a copy of `DeDLOC's tokenizer implementation <https://github.com/yandex-research/DeDLOC/blob/main/sahajbert/tokenizer/tokenizer_model.py>`__ .
14
+
15
+ Custom SentencePiece Unigram Tokenizer with NMT, NKFC, spaces and lower-casing characters normalization
16
+ Represents the Unigram algorithm, with the pretokenization used by SentencePiece
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ replacement: str = "▁",
22
+ add_prefix_space: bool = True,
23
+ unk_token: Union[str, AddedToken] = "<unk>",
24
+ eos_token: Union[str, AddedToken] = "</s>",
25
+ pad_token: Union[str, AddedToken] = "<pad>",
26
+ ):
27
+ self.special_tokens = {
28
+ "pad": {"id": 0, "token": pad_token},
29
+ "eos": {"id": 1, "token": eos_token},
30
+ "unk": {"id": 2, "token": unk_token},
31
+ }
32
+
33
+ self.special_tokens_list = [None] * len(self.special_tokens)
34
+ for token_dict in self.special_tokens.values():
35
+ self.special_tokens_list[token_dict["id"]] = token_dict["token"]
36
+
37
+ tokenizer = Tokenizer(Unigram())
38
+
39
+ tokenizer.normalizer = normalizers.Sequence(
40
+ [
41
+ normalizers.Nmt(),
42
+ normalizers.NFKC(),
43
+ normalizers.Replace(Regex(" {2,}"), " "),
44
+ #normalizers.Lowercase(),
45
+ ]
46
+ )
47
+ tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
48
+ [
49
+ pre_tokenizers.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space),
50
+ pre_tokenizers.Digits(individual_digits=True),
51
+ pre_tokenizers.Punctuation(),
52
+ ]
53
+ )
54
+ tokenizer.decoder = decoders.Metaspace(replacement=replacement, add_prefix_space=add_prefix_space)
55
+
56
+ tokenizer.post_processor = TemplateProcessing(
57
+ single=f"$A {self.special_tokens['eos']['token']}",
58
+ special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])],
59
+ )
60
+
61
+ parameters = {
62
+ "model": "SentencePieceUnigram",
63
+ "replacement": replacement,
64
+ "add_prefix_space": add_prefix_space,
65
+ }
66
+
67
+ super().__init__(tokenizer, parameters)
68
+
69
+ def train(
70
+ self,
71
+ files: Union[str, List[str]],
72
+ vocab_size: int = 8000,
73
+ show_progress: bool = True,
74
+ ):
75
+ """Train the model using the given files"""
76
+
77
+ trainer = trainers.UnigramTrainer(
78
+ vocab_size=vocab_size,
79
+ special_tokens=self.special_tokens_list,
80
+ show_progress=show_progress,
81
+ )
82
+
83
+ if isinstance(files, str):
84
+ files = [files]
85
+ self._tokenizer.train(files, trainer=trainer)
86
+
87
+ self.add_unk_id()
88
+
89
+ def train_from_iterator(
90
+ self,
91
+ iterator: Union[Iterator[str], Iterator[Iterator[str]]],
92
+ vocab_size: int = 8000,
93
+ show_progress: bool = True,
94
+ ):
95
+ """Train the model using the given iterator"""
96
+
97
+ trainer = trainers.UnigramTrainer(
98
+ vocab_size=vocab_size,
99
+ special_tokens=self.special_tokens_list,
100
+ show_progress=show_progress,
101
+ )
102
+
103
+ self._tokenizer.train_from_iterator(iterator, trainer=trainer)
104
+
105
+ self.add_unk_id()
106
+
107
+ def add_unk_id(self):
108
+ tokenizer_json = json.loads(self._tokenizer.to_str())
109
+
110
+ tokenizer_json["model"]["unk_id"] = self.special_tokens["unk"]["id"]
111
+
112
+ self._tokenizer = Tokenizer.from_str(json.dumps(tokenizer_json))
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>", "extra_ids": 100, "additional_special_tokens": ["<extra_id_0>", "<extra_id_1>", "<extra_id_2>", "<extra_id_3>", "<extra_id_4>", "<extra_id_5>", "<extra_id_6>", "<extra_id_7>", "<extra_id_8>", "<extra_id_9>", "<extra_id_10>", "<extra_id_11>", "<extra_id_12>", "<extra_id_13>", "<extra_id_14>", "<extra_id_15>", "<extra_id_16>", "<extra_id_17>", "<extra_id_18>", "<extra_id_19>", "<extra_id_20>", "<extra_id_21>", "<extra_id_22>", "<extra_id_23>", "<extra_id_24>", "<extra_id_25>", "<extra_id_26>", "<extra_id_27>", "<extra_id_28>", "<extra_id_29>", "<extra_id_30>", "<extra_id_31>", "<extra_id_32>", "<extra_id_33>", "<extra_id_34>", "<extra_id_35>", "<extra_id_36>", "<extra_id_37>", "<extra_id_38>", "<extra_id_39>", "<extra_id_40>", "<extra_id_41>", "<extra_id_42>", "<extra_id_43>", "<extra_id_44>", "<extra_id_45>", "<extra_id_46>", "<extra_id_47>", "<extra_id_48>", "<extra_id_49>", "<extra_id_50>", "<extra_id_51>", "<extra_id_52>", "<extra_id_53>", "<extra_id_54>", "<extra_id_55>", "<extra_id_56>", "<extra_id_57>", "<extra_id_58>", "<extra_id_59>", "<extra_id_60>", "<extra_id_61>", "<extra_id_62>", "<extra_id_63>", "<extra_id_64>", "<extra_id_65>", "<extra_id_66>", "<extra_id_67>", "<extra_id_68>", "<extra_id_69>", "<extra_id_70>", "<extra_id_71>", "<extra_id_72>", "<extra_id_73>", "<extra_id_74>", "<extra_id_75>", "<extra_id_76>", "<extra_id_77>", "<extra_id_78>", "<extra_id_79>", "<extra_id_80>", "<extra_id_81>", "<extra_id_82>", "<extra_id_83>", "<extra_id_84>", "<extra_id_85>", "<extra_id_86>", "<extra_id_87>", "<extra_id_88>", "<extra_id_89>", "<extra_id_90>", "<extra_id_91>", "<extra_id_92>", "<extra_id_93>", "<extra_id_94>", "<extra_id_95>", "<extra_id_96>", "<extra_id_97>", "<extra_id_98>", "<extra_id_99>"], "use_fast": true, "special_tokens_map_file": null, "name_or_path": ".", "from_flax": true, "tokenizer_class": "T5Tokenizer"}
train_tokenizer.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset, concatenate_datasets
2
+ from tokenizers import trainers, Tokenizer, normalizers
3
+ from t5_tokenizer_model import SentencePieceUnigramTokenizer
4
+
5
+
6
+ vocab_size = 50_000
7
+ input_sentence_size = None
8
+ model_dir = "./" # ${MODEL_DIR}
9
+
10
+ # Initialize a dataset
11
+ dataset = load_dataset("json", data_files=["/mnt/disks/flaxdisk/corpus/norwegian_colossal_corpus_validation.json","/mnt/disks/flaxdisk/corpus/special_chars.json"], split='train')
12
+
13
+ tokenizer = SentencePieceUnigramTokenizer(unk_token="<unk>", eos_token="</s>", pad_token="<pad>")
14
+
15
+
16
+ # Build an iterator over this dataset
17
+ def batch_iterator(input_sentence_size=None):
18
+ if input_sentence_size is None:
19
+ input_sentence_size = len(dataset)
20
+ batch_length = 100
21
+ for i in range(0, input_sentence_size, batch_length):
22
+ yield dataset[i: i + batch_length]["text"]
23
+
24
+
25
+ # Train tokenizer
26
+ tokenizer.train_from_iterator(
27
+ iterator=batch_iterator(input_sentence_size=input_sentence_size),
28
+ vocab_size=vocab_size,
29
+ show_progress=True,
30
+ )
31
+
32
+ # Save files to disk
33
+ tokenizer.save(f"{model_dir}/tokenizer.json")
34
+