ibraheemmoosa
commited on
Commit
•
ebed999
1
Parent(s):
c43ef85
prev run
Browse files- config.json +1 -1
- prev-checkpoint/config.json +56 -0
- prev-checkpoint/flax_model.msgpack +3 -0
- tokenizer.json → prev-checkpoint/tokenizer.json +0 -0
- run_t5_mlm_flax.py +785 -0
- t5-train.sh +9 -8
- tokenizer/config.json +56 -0
- tokenizer/tokenizer.json +0 -0
- train_unigram_tokenizer.py +20 -0
config.json
CHANGED
@@ -50,7 +50,7 @@
|
|
50 |
"prefix": "translate English to Romanian: "
|
51 |
}
|
52 |
},
|
53 |
-
"transformers_version": "4.
|
54 |
"use_cache": true,
|
55 |
"vocab_size": 32128
|
56 |
}
|
|
|
50 |
"prefix": "translate English to Romanian: "
|
51 |
}
|
52 |
},
|
53 |
+
"transformers_version": "4.9.0.dev0",
|
54 |
"use_cache": true,
|
55 |
"vocab_size": 32128
|
56 |
}
|
prev-checkpoint/config.json
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"T5ForConditionalGeneration"
|
4 |
+
],
|
5 |
+
"d_ff": 2048,
|
6 |
+
"d_kv": 64,
|
7 |
+
"d_model": 512,
|
8 |
+
"decoder_start_token_id": 0,
|
9 |
+
"dropout_rate": 0.1,
|
10 |
+
"eos_token_id": 1,
|
11 |
+
"feed_forward_proj": "relu",
|
12 |
+
"gradient_checkpointing": false,
|
13 |
+
"initializer_factor": 1.0,
|
14 |
+
"is_encoder_decoder": true,
|
15 |
+
"layer_norm_epsilon": 1e-06,
|
16 |
+
"model_type": "t5",
|
17 |
+
"n_positions": 512,
|
18 |
+
"num_decoder_layers": 6,
|
19 |
+
"num_heads": 8,
|
20 |
+
"num_layers": 6,
|
21 |
+
"output_past": true,
|
22 |
+
"pad_token_id": 0,
|
23 |
+
"relative_attention_num_buckets": 32,
|
24 |
+
"task_specific_params": {
|
25 |
+
"summarization": {
|
26 |
+
"early_stopping": true,
|
27 |
+
"length_penalty": 2.0,
|
28 |
+
"max_length": 200,
|
29 |
+
"min_length": 30,
|
30 |
+
"no_repeat_ngram_size": 3,
|
31 |
+
"num_beams": 4,
|
32 |
+
"prefix": "summarize: "
|
33 |
+
},
|
34 |
+
"translation_en_to_de": {
|
35 |
+
"early_stopping": true,
|
36 |
+
"max_length": 300,
|
37 |
+
"num_beams": 4,
|
38 |
+
"prefix": "translate English to German: "
|
39 |
+
},
|
40 |
+
"translation_en_to_fr": {
|
41 |
+
"early_stopping": true,
|
42 |
+
"max_length": 300,
|
43 |
+
"num_beams": 4,
|
44 |
+
"prefix": "translate English to French: "
|
45 |
+
},
|
46 |
+
"translation_en_to_ro": {
|
47 |
+
"early_stopping": true,
|
48 |
+
"max_length": 300,
|
49 |
+
"num_beams": 4,
|
50 |
+
"prefix": "translate English to Romanian: "
|
51 |
+
}
|
52 |
+
},
|
53 |
+
"transformers_version": "4.9.0.dev0",
|
54 |
+
"use_cache": true,
|
55 |
+
"vocab_size": 32103
|
56 |
+
}
|
prev-checkpoint/flax_model.msgpack
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cce32bdbfd64afb9c1130663f9c1ff4264cb079220c5e68d292a58465f7d2780
|
3 |
+
size 241981002
|
tokenizer.json → prev-checkpoint/tokenizer.json
RENAMED
File without changes
|
run_t5_mlm_flax.py
ADDED
@@ -0,0 +1,785 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
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 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
475 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
476 |
+
|
477 |
+
# Load pretrained model and tokenizer
|
478 |
+
|
479 |
+
if model_args.tokenizer_name:
|
480 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
481 |
+
model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
482 |
+
)
|
483 |
+
elif model_args.model_name_or_path:
|
484 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
485 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
|
486 |
+
)
|
487 |
+
else:
|
488 |
+
raise ValueError(
|
489 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
490 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
491 |
+
)
|
492 |
+
|
493 |
+
if model_args.config_name:
|
494 |
+
config = T5Config.from_pretrained(
|
495 |
+
model_args.config_name, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
|
496 |
+
)
|
497 |
+
elif model_args.model_name_or_path:
|
498 |
+
config = T5Config.from_pretrained(
|
499 |
+
model_args.model_name_or_path, cache_dir=model_args.cache_dir, vocab_size=len(tokenizer)
|
500 |
+
)
|
501 |
+
else:
|
502 |
+
config = CONFIG_MAPPING[model_args.model_type]()
|
503 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
504 |
+
|
505 |
+
# Preprocessing the datasets.
|
506 |
+
# First we tokenize all the texts.
|
507 |
+
if training_args.do_train:
|
508 |
+
column_names = datasets["train"].column_names
|
509 |
+
else:
|
510 |
+
column_names = datasets["validation"].column_names
|
511 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
512 |
+
|
513 |
+
max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
|
514 |
+
|
515 |
+
# Otherwise, we tokenize every text, then concatenate them together before splitting them in smaller parts.
|
516 |
+
# Since we make sure that all sequences are of the same length, no attention_mask is needed.
|
517 |
+
def tokenize_function(examples):
|
518 |
+
return tokenizer(examples[text_column_name], return_attention_mask=False)
|
519 |
+
|
520 |
+
tokenized_datasets = datasets.map(
|
521 |
+
tokenize_function,
|
522 |
+
batched=True,
|
523 |
+
num_proc=data_args.preprocessing_num_workers,
|
524 |
+
remove_columns=column_names,
|
525 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
526 |
+
)
|
527 |
+
|
528 |
+
# T5-like span masked language modeling will fuse consecutively masked tokens to a single sentinel token.
|
529 |
+
# To ensure that the input length is `max_seq_length`, we need to increase the maximum length
|
530 |
+
# according to `mlm_probability` and `mean_noise_span_length`. We can also define the label length accordingly.
|
531 |
+
expanded_inputs_length, targets_length = compute_input_and_target_lengths(
|
532 |
+
inputs_length=max_seq_length,
|
533 |
+
noise_density=data_args.mlm_probability,
|
534 |
+
mean_noise_span_length=data_args.mean_noise_span_length,
|
535 |
+
)
|
536 |
+
|
537 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of expanded_inputs_length.
|
538 |
+
def group_texts(examples):
|
539 |
+
# Concatenate all texts.
|
540 |
+
concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
|
541 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
542 |
+
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
|
543 |
+
# customize this part to your needs.
|
544 |
+
if total_length >= expanded_inputs_length:
|
545 |
+
total_length = (total_length // expanded_inputs_length) * expanded_inputs_length
|
546 |
+
# Split by chunks of max_len.
|
547 |
+
result = {
|
548 |
+
k: [t[i : i + expanded_inputs_length] for i in range(0, total_length, expanded_inputs_length)]
|
549 |
+
for k, t in concatenated_examples.items()
|
550 |
+
}
|
551 |
+
return result
|
552 |
+
|
553 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a
|
554 |
+
# remainder for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value
|
555 |
+
# might be slower to preprocess.
|
556 |
+
#
|
557 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
558 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
559 |
+
tokenized_datasets = tokenized_datasets.map(
|
560 |
+
group_texts,
|
561 |
+
batched=True,
|
562 |
+
num_proc=data_args.preprocessing_num_workers,
|
563 |
+
load_from_cache_file=not data_args.overwrite_cache,
|
564 |
+
)
|
565 |
+
|
566 |
+
# Enable tensorboard only on the master node
|
567 |
+
has_tensorboard = is_tensorboard_available()
|
568 |
+
if has_tensorboard and jax.process_index() == 0:
|
569 |
+
try:
|
570 |
+
from flax.metrics.tensorboard import SummaryWriter
|
571 |
+
|
572 |
+
summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
|
573 |
+
except ImportError as ie:
|
574 |
+
has_tensorboard = False
|
575 |
+
logger.warning(
|
576 |
+
f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
|
577 |
+
)
|
578 |
+
else:
|
579 |
+
logger.warning(
|
580 |
+
"Unable to display metrics through TensorBoard because the package is not installed: "
|
581 |
+
"Please run pip install tensorboard to enable."
|
582 |
+
)
|
583 |
+
|
584 |
+
# Initialize our training
|
585 |
+
rng = jax.random.PRNGKey(training_args.seed)
|
586 |
+
dropout_rngs = jax.random.split(rng, jax.local_device_count())
|
587 |
+
|
588 |
+
if model_args.model_name_or_path:
|
589 |
+
model = FlaxT5ForConditionalGeneration.from_pretrained(
|
590 |
+
model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
|
591 |
+
)
|
592 |
+
else:
|
593 |
+
model = FlaxT5ForConditionalGeneration(config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype))
|
594 |
+
|
595 |
+
# Data collator
|
596 |
+
# This one will take care of randomly masking the tokens.
|
597 |
+
data_collator = FlaxDataCollatorForT5MLM(
|
598 |
+
tokenizer=tokenizer,
|
599 |
+
noise_density=data_args.mlm_probability,
|
600 |
+
mean_noise_span_length=data_args.mean_noise_span_length,
|
601 |
+
input_length=max_seq_length,
|
602 |
+
target_length=targets_length,
|
603 |
+
pad_token_id=model.config.pad_token_id,
|
604 |
+
decoder_start_token_id=model.config.decoder_start_token_id,
|
605 |
+
)
|
606 |
+
|
607 |
+
# Store some constant
|
608 |
+
num_epochs = int(training_args.num_train_epochs)
|
609 |
+
train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
|
610 |
+
eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
|
611 |
+
|
612 |
+
num_train_steps = len(tokenized_datasets["train"]) // train_batch_size * num_epochs
|
613 |
+
|
614 |
+
# Create learning rate schedule
|
615 |
+
warmup_fn = optax.linear_schedule(
|
616 |
+
init_value=0.0, end_value=training_args.learning_rate, transition_steps=training_args.warmup_steps
|
617 |
+
)
|
618 |
+
decay_fn = optax.linear_schedule(
|
619 |
+
init_value=training_args.learning_rate,
|
620 |
+
end_value=0,
|
621 |
+
transition_steps=num_train_steps - training_args.warmup_steps,
|
622 |
+
)
|
623 |
+
linear_decay_lr_schedule_fn = optax.join_schedules(
|
624 |
+
schedules=[warmup_fn, decay_fn], boundaries=[training_args.warmup_steps]
|
625 |
+
)
|
626 |
+
|
627 |
+
# We use Optax's "masking" functionality to not apply weight decay
|
628 |
+
# to bias and LayerNorm scale parameters. decay_mask_fn returns a
|
629 |
+
# mask boolean with the same structure as the parameters.
|
630 |
+
# The mask is True for parameters that should be decayed.
|
631 |
+
def decay_mask_fn(params):
|
632 |
+
flat_params = traverse_util.flatten_dict(params)
|
633 |
+
flat_mask = {
|
634 |
+
path: (path[-1] != "bias" and path[-2:] not in [("layer_norm", "scale"), ("final_layer_norm", "scale")])
|
635 |
+
for path in flat_params
|
636 |
+
}
|
637 |
+
return traverse_util.unflatten_dict(flat_mask)
|
638 |
+
|
639 |
+
# create adam optimizer
|
640 |
+
if training_args.adafactor:
|
641 |
+
# We use the default parameters here to initialize adafactor,
|
642 |
+
# For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
|
643 |
+
optimizer = optax.adafactor(
|
644 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
645 |
+
)
|
646 |
+
else:
|
647 |
+
optimizer = optax.adamw(
|
648 |
+
learning_rate=linear_decay_lr_schedule_fn,
|
649 |
+
b1=training_args.adam_beta1,
|
650 |
+
b2=training_args.adam_beta2,
|
651 |
+
weight_decay=training_args.weight_decay,
|
652 |
+
mask=decay_mask_fn,
|
653 |
+
)
|
654 |
+
|
655 |
+
# Setup train state
|
656 |
+
state = train_state.TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer)
|
657 |
+
|
658 |
+
# Define gradient update step fn
|
659 |
+
def train_step(state, batch, dropout_rng):
|
660 |
+
dropout_rng, new_dropout_rng = jax.random.split(dropout_rng)
|
661 |
+
|
662 |
+
def loss_fn(params):
|
663 |
+
labels = batch.pop("labels")
|
664 |
+
|
665 |
+
logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
|
666 |
+
|
667 |
+
# compute loss
|
668 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1])).mean()
|
669 |
+
|
670 |
+
return loss
|
671 |
+
|
672 |
+
grad_fn = jax.value_and_grad(loss_fn)
|
673 |
+
loss, grad = grad_fn(state.params)
|
674 |
+
grad = jax.lax.pmean(grad, "batch")
|
675 |
+
new_state = state.apply_gradients(grads=grad)
|
676 |
+
|
677 |
+
metrics = jax.lax.pmean(
|
678 |
+
{"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}, axis_name="batch"
|
679 |
+
)
|
680 |
+
|
681 |
+
return new_state, metrics, new_dropout_rng
|
682 |
+
|
683 |
+
# Create parallel version of the train step
|
684 |
+
p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
|
685 |
+
|
686 |
+
# Define eval fn
|
687 |
+
def eval_step(params, batch):
|
688 |
+
labels = batch.pop("labels")
|
689 |
+
|
690 |
+
logits = model(**batch, params=params, train=False)[0]
|
691 |
+
|
692 |
+
# compute loss
|
693 |
+
loss = optax.softmax_cross_entropy(logits, onehot(labels, logits.shape[-1]))
|
694 |
+
|
695 |
+
# compute accuracy
|
696 |
+
accuracy = jnp.equal(jnp.argmax(logits, axis=-1), labels)
|
697 |
+
|
698 |
+
# summarize metrics
|
699 |
+
metrics = {"loss": loss.mean(), "accuracy": accuracy.mean()}
|
700 |
+
metrics = jax.lax.pmean(metrics, axis_name="batch")
|
701 |
+
|
702 |
+
return metrics
|
703 |
+
|
704 |
+
p_eval_step = jax.pmap(eval_step, "batch", donate_argnums=(0,))
|
705 |
+
|
706 |
+
# Replicate the train state on each device
|
707 |
+
state = jax_utils.replicate(state)
|
708 |
+
|
709 |
+
train_time = 0
|
710 |
+
epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
|
711 |
+
for epoch in epochs:
|
712 |
+
# ======================== Training ================================
|
713 |
+
train_start = time.time()
|
714 |
+
train_metrics = []
|
715 |
+
|
716 |
+
# Create sampling rng
|
717 |
+
rng, input_rng = jax.random.split(rng)
|
718 |
+
|
719 |
+
# Generate an epoch by shuffling sampling indices from the train dataset
|
720 |
+
num_train_samples = len(tokenized_datasets["train"])
|
721 |
+
train_samples_idx = jax.random.permutation(input_rng, jnp.arange(num_train_samples))
|
722 |
+
train_batch_idx = generate_batch_splits(train_samples_idx, train_batch_size)
|
723 |
+
|
724 |
+
# Gather the indexes for creating the batch and do a training step
|
725 |
+
for step, batch_idx in enumerate(tqdm(train_batch_idx, desc="Training...", position=1)):
|
726 |
+
samples = [tokenized_datasets["train"][int(idx)] for idx in batch_idx]
|
727 |
+
model_inputs = data_collator(samples)
|
728 |
+
|
729 |
+
# Model forward
|
730 |
+
model_inputs = shard(model_inputs.data)
|
731 |
+
state, train_metric, dropout_rngs = p_train_step(state, model_inputs, dropout_rngs)
|
732 |
+
train_metrics.append(train_metric)
|
733 |
+
|
734 |
+
cur_step = epoch * (num_train_samples // train_batch_size) + step
|
735 |
+
|
736 |
+
if cur_step % training_args.logging_steps == 0 and cur_step > 0:
|
737 |
+
# Save metrics
|
738 |
+
train_metric = jax_utils.unreplicate(train_metric)
|
739 |
+
train_time += time.time() - train_start
|
740 |
+
if has_tensorboard and jax.process_index() == 0:
|
741 |
+
write_train_metric(summary_writer, train_metrics, train_time, cur_step)
|
742 |
+
|
743 |
+
epochs.write(
|
744 |
+
f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
|
745 |
+
)
|
746 |
+
|
747 |
+
train_metrics = []
|
748 |
+
|
749 |
+
if cur_step % training_args.eval_steps == 0 and cur_step > 0:
|
750 |
+
# ======================== Evaluating ==============================
|
751 |
+
num_eval_samples = len(tokenized_datasets["validation"])
|
752 |
+
eval_samples_idx = jnp.arange(num_eval_samples)
|
753 |
+
eval_batch_idx = generate_batch_splits(eval_samples_idx, eval_batch_size)
|
754 |
+
|
755 |
+
eval_metrics = []
|
756 |
+
for i, batch_idx in enumerate(tqdm(eval_batch_idx, desc="Evaluating ...", position=2)):
|
757 |
+
samples = [tokenized_datasets["validation"][int(idx)] for idx in batch_idx]
|
758 |
+
model_inputs = data_collator(samples)
|
759 |
+
|
760 |
+
# Model forward
|
761 |
+
model_inputs = shard(model_inputs.data)
|
762 |
+
metrics = p_eval_step(state.params, model_inputs)
|
763 |
+
eval_metrics.append(metrics)
|
764 |
+
|
765 |
+
# get eval metrics
|
766 |
+
eval_metrics = get_metrics(eval_metrics)
|
767 |
+
eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
|
768 |
+
|
769 |
+
# Update progress bar
|
770 |
+
epochs.write(f"Step... ({cur_step} | Loss: {eval_metrics['loss']}, Acc: {eval_metrics['accuracy']})")
|
771 |
+
|
772 |
+
# Save metrics
|
773 |
+
if has_tensorboard and jax.process_index() == 0:
|
774 |
+
write_eval_metric(summary_writer, eval_metrics, cur_step)
|
775 |
+
|
776 |
+
if cur_step % training_args.save_steps == 0 and cur_step > 0:
|
777 |
+
# save checkpoint after each epoch and push checkpoint to the hub
|
778 |
+
if jax.process_index() == 0:
|
779 |
+
params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
|
780 |
+
model.save_pretrained(
|
781 |
+
training_args.output_dir,
|
782 |
+
params=params,
|
783 |
+
push_to_hub=training_args.push_to_hub,
|
784 |
+
commit_message=f"Saving weights and logs of step {cur_step}",
|
785 |
+
)
|
t5-train.sh
CHANGED
@@ -1,11 +1,12 @@
|
|
1 |
#!/bin/bash
|
2 |
HF_DATASETS_IN_MEMORY_MAX_SIZE=200000000
|
3 |
-
MODEL_DIR=
|
4 |
-
|
|
|
5 |
--output_dir="${MODEL_DIR}" \
|
6 |
--model_type="t5" \
|
7 |
-
--config_name="
|
8 |
-
--tokenizer_name="${
|
9 |
--dataset_name="mc4" \
|
10 |
--dataset_config_name="bn" \
|
11 |
--max_seq_length="512" \
|
@@ -16,7 +17,7 @@ run_t5_mlm_flax.py \
|
|
16 |
--warmup_steps="500" \
|
17 |
--overwrite_output_dir \
|
18 |
--num_train_epochs="10" \
|
19 |
-
--logging_steps="
|
20 |
-
--save_steps="
|
21 |
-
--eval_steps="
|
22 |
-
|
|
|
1 |
#!/bin/bash
|
2 |
HF_DATASETS_IN_MEMORY_MAX_SIZE=200000000
|
3 |
+
MODEL_DIR=checkpoints
|
4 |
+
TOKENIZER_DIR=tokenizer
|
5 |
+
./run_t5_mlm_flax.py \
|
6 |
--output_dir="${MODEL_DIR}" \
|
7 |
--model_type="t5" \
|
8 |
+
--config_name="t5-small" \
|
9 |
+
--tokenizer_name="${TOKENIZER_DIR}" \
|
10 |
--dataset_name="mc4" \
|
11 |
--dataset_config_name="bn" \
|
12 |
--max_seq_length="512" \
|
|
|
17 |
--warmup_steps="500" \
|
18 |
--overwrite_output_dir \
|
19 |
--num_train_epochs="10" \
|
20 |
+
--logging_steps="1" \
|
21 |
+
--save_steps="1" \
|
22 |
+
--eval_steps="1" \
|
23 |
+
--push_to_hub
|
tokenizer/config.json
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"T5WithLMHeadModel"
|
4 |
+
],
|
5 |
+
"d_ff": 2048,
|
6 |
+
"d_kv": 64,
|
7 |
+
"d_model": 512,
|
8 |
+
"decoder_start_token_id": 0,
|
9 |
+
"dropout_rate": 0.1,
|
10 |
+
"eos_token_id": 1,
|
11 |
+
"feed_forward_proj": "relu",
|
12 |
+
"gradient_checkpointing": false,
|
13 |
+
"initializer_factor": 1.0,
|
14 |
+
"is_encoder_decoder": true,
|
15 |
+
"layer_norm_epsilon": 1e-06,
|
16 |
+
"model_type": "t5",
|
17 |
+
"n_positions": 512,
|
18 |
+
"num_decoder_layers": 6,
|
19 |
+
"num_heads": 8,
|
20 |
+
"num_layers": 6,
|
21 |
+
"output_past": true,
|
22 |
+
"pad_token_id": 0,
|
23 |
+
"relative_attention_num_buckets": 32,
|
24 |
+
"task_specific_params": {
|
25 |
+
"summarization": {
|
26 |
+
"early_stopping": true,
|
27 |
+
"length_penalty": 2.0,
|
28 |
+
"max_length": 200,
|
29 |
+
"min_length": 30,
|
30 |
+
"no_repeat_ngram_size": 3,
|
31 |
+
"num_beams": 4,
|
32 |
+
"prefix": "summarize: "
|
33 |
+
},
|
34 |
+
"translation_en_to_de": {
|
35 |
+
"early_stopping": true,
|
36 |
+
"max_length": 300,
|
37 |
+
"num_beams": 4,
|
38 |
+
"prefix": "translate English to German: "
|
39 |
+
},
|
40 |
+
"translation_en_to_fr": {
|
41 |
+
"early_stopping": true,
|
42 |
+
"max_length": 300,
|
43 |
+
"num_beams": 4,
|
44 |
+
"prefix": "translate English to French: "
|
45 |
+
},
|
46 |
+
"translation_en_to_ro": {
|
47 |
+
"early_stopping": true,
|
48 |
+
"max_length": 300,
|
49 |
+
"num_beams": 4,
|
50 |
+
"prefix": "translate English to Romanian: "
|
51 |
+
}
|
52 |
+
},
|
53 |
+
"transformers_version": "4.9.0.dev0",
|
54 |
+
"use_cache": true,
|
55 |
+
"vocab_size": 32128
|
56 |
+
}
|
tokenizer/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
train_unigram_tokenizer.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from tokenizers import Tokenizer
|
2 |
+
from tokenizers.models import Unigram
|
3 |
+
from tokenizers.trainers import UnigramTrainer
|
4 |
+
from tokenizers.normalizers import NFKC
|
5 |
+
from tokenizers.pre_tokenizers import UnicodeScripts, Digits, Sequence
|
6 |
+
from datasets import load_dataset
|
7 |
+
|
8 |
+
mc4 = load_dataset('mc4', 'bn', split='train')
|
9 |
+
|
10 |
+
def batch_iterator(dataset, batch_size=1000):
|
11 |
+
for i in range(0, len(dataset), batch_size):
|
12 |
+
yield dataset[i: i + batch_size]["text"]
|
13 |
+
|
14 |
+
tokenizer = Tokenizer(Unigram())
|
15 |
+
tokenizer.normalizer = NFKC()
|
16 |
+
tokenizer.pre_tokenizer = Sequence([UnicodeScripts(), Digits(individual_digits=True)])
|
17 |
+
trainer = UnigramTrainer(vocab_size=32000, special_tokens=['<s>', '<pad>', '</s>', '<unk>', '<mask>'])
|
18 |
+
tokenizer.train_from_iterator(batch_iterator(mc4), trainer=trainer, length=len(mc4))
|
19 |
+
tokenizer.save('tokenizer-mc4-unigram.json')
|
20 |
+
|