imthanhlv commited on
Commit
99b6635
1 Parent(s): d4587a0

first commit

Browse files
Files changed (6) hide show
  1. config.json +39 -0
  2. create_config.py +4 -0
  3. requirements.txt +5 -0
  4. run_clm_flax.py +766 -0
  5. tokenizer.json +0 -0
  6. train_tokenizer.py +24 -0
config.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "gelu_new",
3
+ "architectures": [
4
+ "GPT2LMHeadModel"
5
+ ],
6
+ "attn_pdrop": 0.0,
7
+ "bos_token_id": 50256,
8
+ "embd_pdrop": 0.0,
9
+ "eos_token_id": 50256,
10
+ "initializer_range": 0.02,
11
+ "layer_norm_epsilon": 1e-05,
12
+ "model_type": "gpt2",
13
+ "n_ctx": 1024,
14
+ "n_embd": 1024,
15
+ "n_head": 16,
16
+ "n_inner": null,
17
+ "n_layer": 24,
18
+ "n_positions": 1024,
19
+ "n_special": 0,
20
+ "predict_special_tokens": true,
21
+ "reorder_and_upcast_attn": false,
22
+ "resid_pdrop": 0.0,
23
+ "scale_attn_by_inverse_layer_idx": false,
24
+ "scale_attn_weights": true,
25
+ "summary_activation": null,
26
+ "summary_first_dropout": 0.1,
27
+ "summary_proj_to_labels": true,
28
+ "summary_type": "cls_index",
29
+ "summary_use_proj": true,
30
+ "task_specific_params": {
31
+ "text-generation": {
32
+ "do_sample": true,
33
+ "max_length": 50
34
+ }
35
+ },
36
+ "transformers_version": "4.16.0.dev0",
37
+ "use_cache": true,
38
+ "vocab_size": 50257
39
+ }
create_config.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from transformers import GPT2Config
2
+
3
+ config = GPT2Config.from_pretrained("gpt2-medium", resid_pdrop=0.0, embd_pdrop=0.0, attn_pdrop=0.0, vocab_size=50257)
4
+ config.save_pretrained(".")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ datasets >= 1.1.3
2
+ jax>=0.2.8
3
+ jaxlib>=0.1.59
4
+ flax>=0.3.5
5
+ optax>=0.0.9
run_clm_flax.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Pre-training/Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) on a text file or a dataset.
18
+
19
+ Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
20
+ https://huggingface.co/models?filter=text-generation
21
+ """
22
+ # You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
23
+
24
+ import json
25
+ import logging
26
+ import math
27
+ import os
28
+ import sys
29
+ import time
30
+ from dataclasses import asdict, dataclass, field
31
+ from enum import Enum
32
+ from itertools import chain
33
+ from pathlib import Path
34
+ from typing import Callable, Optional
35
+
36
+ import datasets
37
+ import numpy as np
38
+ from datasets import Dataset, load_dataset
39
+ from tqdm import tqdm
40
+
41
+ import jax
42
+ import jax.numpy as jnp
43
+ import optax
44
+ import transformers
45
+ from flax import jax_utils, traverse_util
46
+ from flax.jax_utils import unreplicate
47
+ from flax.training import train_state
48
+ from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
49
+ from huggingface_hub import Repository
50
+ from transformers import (
51
+ CONFIG_MAPPING,
52
+ FLAX_MODEL_FOR_CAUSAL_LM_MAPPING,
53
+ AutoConfig,
54
+ AutoTokenizer,
55
+ FlaxAutoModelForCausalLM,
56
+ HfArgumentParser,
57
+ is_tensorboard_available,
58
+ set_seed,
59
+ )
60
+ from transformers.file_utils import get_full_repo_name
61
+ from transformers.testing_utils import CaptureLogger
62
+
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_CAUSAL_LM_MAPPING.keys())
67
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
68
+
69
+
70
+ @dataclass
71
+ class TrainingArguments:
72
+ output_dir: str = field(
73
+ metadata={"help": "The output directory where the model predictions and checkpoints will be written."},
74
+ )
75
+ overwrite_output_dir: bool = field(
76
+ default=False,
77
+ metadata={
78
+ "help": (
79
+ "Overwrite the content of the output directory. "
80
+ "Use this to continue training if output_dir points to a checkpoint directory."
81
+ )
82
+ },
83
+ )
84
+ do_train: bool = field(default=False, metadata={"help": "Whether to run training."})
85
+ do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})
86
+ per_device_train_batch_size: int = field(
87
+ default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."}
88
+ )
89
+ per_device_eval_batch_size: int = field(
90
+ default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}
91
+ )
92
+ learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
93
+ weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
94
+ adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
95
+ adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
96
+ adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
97
+ adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
98
+ num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
99
+ warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."})
100
+ logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."})
101
+ save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."})
102
+ eval_steps: int = field(default=None, metadata={"help": "Run an evaluation every X steps."})
103
+ seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."})
104
+ push_to_hub: bool = field(
105
+ default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."}
106
+ )
107
+ hub_model_id: str = field(
108
+ default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."}
109
+ )
110
+ hub_token: str = field(default=None, metadata={"help": "The token to use to push to the Model Hub."})
111
+
112
+ def __post_init__(self):
113
+ if self.output_dir is not None:
114
+ self.output_dir = os.path.expanduser(self.output_dir)
115
+
116
+ def to_dict(self):
117
+ """
118
+ Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates
119
+ the token values by removing their value.
120
+ """
121
+ d = asdict(self)
122
+ for k, v in d.items():
123
+ if isinstance(v, Enum):
124
+ d[k] = v.value
125
+ if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum):
126
+ d[k] = [x.value for x in v]
127
+ if k.endswith("_token"):
128
+ d[k] = f"<{k.upper()}>"
129
+ return d
130
+
131
+
132
+ @dataclass
133
+ class ModelArguments:
134
+ """
135
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
136
+ """
137
+
138
+ model_name_or_path: Optional[str] = field(
139
+ default=None,
140
+ metadata={
141
+ "help": "The model checkpoint for weights initialization."
142
+ "Don't set if you want to train a model from scratch."
143
+ },
144
+ )
145
+ model_type: Optional[str] = field(
146
+ default=None,
147
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
148
+ )
149
+ config_name: Optional[str] = field(
150
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
151
+ )
152
+ tokenizer_name: Optional[str] = field(
153
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
154
+ )
155
+ cache_dir: Optional[str] = field(
156
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
157
+ )
158
+ use_fast_tokenizer: bool = field(
159
+ default=True,
160
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
161
+ )
162
+ dtype: Optional[str] = field(
163
+ default="float32",
164
+ metadata={
165
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
166
+ },
167
+ )
168
+
169
+
170
+ @dataclass
171
+ class DataTrainingArguments:
172
+ """
173
+ Arguments pertaining to what data we are going to input our model for training and eval.
174
+ """
175
+
176
+ dataset_name: Optional[str] = field(
177
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
178
+ )
179
+ dataset_config_name: Optional[str] = field(
180
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
181
+ )
182
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
183
+ validation_file: Optional[str] = field(
184
+ default=None,
185
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
186
+ )
187
+ max_train_samples: Optional[int] = field(
188
+ default=None,
189
+ metadata={
190
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
191
+ "value if set."
192
+ },
193
+ )
194
+ max_eval_samples: Optional[int] = field(
195
+ default=None,
196
+ metadata={
197
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
198
+ "value if set."
199
+ },
200
+ )
201
+ overwrite_cache: bool = field(
202
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
203
+ )
204
+ validation_split_percentage: Optional[int] = field(
205
+ default=5,
206
+ metadata={
207
+ "help": "The percentage of the train set used as validation set in case there's no validation split"
208
+ },
209
+ )
210
+ block_size: Optional[int] = field(
211
+ default=None,
212
+ metadata={
213
+ "help": "Optional input sequence length after tokenization. "
214
+ "The training dataset will be truncated in block of this size for training. "
215
+ "Default to the model max input length for single sentence inputs (take into account special tokens)."
216
+ },
217
+ )
218
+ overwrite_cache: bool = field(
219
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
220
+ )
221
+ preprocessing_num_workers: Optional[int] = field(
222
+ default=None,
223
+ metadata={"help": "The number of processes to use for the preprocessing."},
224
+ )
225
+ keep_linebreaks: bool = field(
226
+ default=True, metadata={"help": "Whether to keep line breaks when using TXT files or not."}
227
+ )
228
+
229
+ def __post_init__(self):
230
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
231
+ raise ValueError("Need either a dataset name or a training/validation file.")
232
+ else:
233
+ if self.train_file is not None:
234
+ extension = self.train_file.split(".")[-1]
235
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
236
+ if self.validation_file is not None:
237
+ extension = self.validation_file.split(".")[-1]
238
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."
239
+
240
+
241
+ class TrainState(train_state.TrainState):
242
+ dropout_rng: jnp.ndarray
243
+
244
+ def replicate(self):
245
+ return jax_utils.replicate(self).replace(dropout_rng=shard_prng_key(self.dropout_rng))
246
+
247
+
248
+ def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False):
249
+ """
250
+ Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices.
251
+ Shuffle batches if `shuffle` is `True`.
252
+ """
253
+ steps_per_epoch = len(dataset) // batch_size
254
+
255
+ if shuffle:
256
+ batch_idx = jax.random.permutation(rng, len(dataset))
257
+ else:
258
+ batch_idx = jnp.arange(len(dataset))
259
+
260
+ batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch.
261
+ batch_idx = batch_idx.reshape((steps_per_epoch, batch_size))
262
+
263
+ for idx in batch_idx:
264
+ batch = dataset[idx]
265
+ batch = {k: np.array(v) for k, v in batch.items()}
266
+
267
+ yield batch
268
+
269
+
270
+ def write_train_metric(summary_writer, train_metrics, train_time, step):
271
+ summary_writer.scalar("train_time", train_time, step)
272
+
273
+ train_metrics = get_metrics(train_metrics)
274
+ for key, vals in train_metrics.items():
275
+ tag = f"train_{key}"
276
+ for i, val in enumerate(vals):
277
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
278
+
279
+
280
+ def write_eval_metric(summary_writer, eval_metrics, step):
281
+ for metric_name, value in eval_metrics.items():
282
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
283
+
284
+
285
+ def create_learning_rate_fn(
286
+ train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float
287
+ ) -> Callable[[int], jnp.array]:
288
+ """Returns a linear warmup, linear_decay learning rate function."""
289
+ steps_per_epoch = train_ds_size // train_batch_size
290
+ num_train_steps = steps_per_epoch * num_train_epochs
291
+ warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps)
292
+ decay_fn = optax.linear_schedule(
293
+ init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps
294
+ )
295
+ schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps])
296
+ return schedule_fn
297
+
298
+
299
+ def main():
300
+ # See all possible arguments in src/transformers/training_args.py
301
+ # or by passing the --help flag to this script.
302
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
303
+
304
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
305
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
306
+ # If we pass only one argument to the script and it's the path to a json file,
307
+ # let's parse it to get our arguments.
308
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
309
+ else:
310
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
311
+
312
+ if (
313
+ os.path.exists(training_args.output_dir)
314
+ and os.listdir(training_args.output_dir)
315
+ and training_args.do_train
316
+ and not training_args.overwrite_output_dir
317
+ ):
318
+ raise ValueError(
319
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
320
+ "Use --overwrite_output_dir to overcome."
321
+ )
322
+
323
+ # Make one log on every process with the configuration for debugging.
324
+ logging.basicConfig(
325
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
326
+ datefmt="%m/%d/%Y %H:%M:%S",
327
+ level=logging.INFO,
328
+ )
329
+ # Setup logging, we only want one process per machine to log things on the screen.
330
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
331
+ if jax.process_index() == 0:
332
+ datasets.utils.logging.set_verbosity_warning()
333
+ transformers.utils.logging.set_verbosity_info()
334
+ else:
335
+ datasets.utils.logging.set_verbosity_error()
336
+ transformers.utils.logging.set_verbosity_error()
337
+
338
+ # Set the verbosity to info of the Transformers logger (on main process only):
339
+ logger.info(f"Training/evaluation parameters {training_args}")
340
+
341
+ # Set seed before initializing model.
342
+ set_seed(training_args.seed)
343
+
344
+ # Handle the repository creation
345
+ if training_args.push_to_hub:
346
+ if training_args.hub_model_id is None:
347
+ repo_name = get_full_repo_name(
348
+ Path(training_args.output_dir).absolute().name, token=training_args.hub_token
349
+ )
350
+ else:
351
+ repo_name = training_args.hub_model_id
352
+ repo = Repository(training_args.output_dir, clone_from=repo_name)
353
+
354
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
355
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
356
+ # (the dataset will be downloaded automatically from the datasets Hub).
357
+ #
358
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
359
+ # 'text' is found. You can easily tweak this behavior (see below).
360
+ #
361
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
362
+ # download the dataset.
363
+ if data_args.dataset_name is not None:
364
+ # Downloading and loading a dataset from the hub.
365
+ dataset = load_dataset(
366
+ data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, keep_in_memory=False
367
+ )
368
+
369
+ if "validation" not in dataset.keys():
370
+ dataset["validation"] = load_dataset(
371
+ data_args.dataset_name,
372
+ data_args.dataset_config_name,
373
+ split=f"train[:{data_args.validation_split_percentage}%]",
374
+ cache_dir=model_args.cache_dir,
375
+ )
376
+ dataset["train"] = load_dataset(
377
+ data_args.dataset_name,
378
+ data_args.dataset_config_name,
379
+ split=f"train[{data_args.validation_split_percentage}%:]",
380
+ cache_dir=model_args.cache_dir,
381
+ )
382
+ else:
383
+ data_files = {}
384
+ dataset_args = {}
385
+ if data_args.train_file is not None:
386
+ data_files["train"] = data_args.train_file
387
+ if data_args.validation_file is not None:
388
+ data_files["validation"] = data_args.validation_file
389
+ extension = data_args.train_file.split(".")[-1]
390
+ if extension == "txt":
391
+ extension = "text"
392
+ dataset_args["keep_linebreaks"] = data_args.keep_linebreaks
393
+ dataset = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir, **dataset_args)
394
+
395
+ if "validation" not in dataset.keys():
396
+ dataset["validation"] = load_dataset(
397
+ extension,
398
+ data_files=data_files,
399
+ split=f"train[:{data_args.validation_split_percentage}%]",
400
+ cache_dir=model_args.cache_dir,
401
+ **dataset_args,
402
+ )
403
+ dataset["train"] = load_dataset(
404
+ extension,
405
+ data_files=data_files,
406
+ split=f"train[{data_args.validation_split_percentage}%:]",
407
+ cache_dir=model_args.cache_dir,
408
+ **dataset_args,
409
+ )
410
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
411
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
412
+
413
+ # Load pretrained model and tokenizer
414
+
415
+ # Distributed training:
416
+ # The .from_pretrained methods guarantee that only one local process can concurrently
417
+ # download model & vocab.
418
+ if model_args.config_name:
419
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
420
+ elif model_args.model_name_or_path:
421
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
422
+ else:
423
+ config = CONFIG_MAPPING[model_args.model_type]()
424
+ logger.warning("You are instantiating a new config instance from scratch.")
425
+
426
+ if model_args.tokenizer_name:
427
+ tokenizer = AutoTokenizer.from_pretrained(
428
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
429
+ )
430
+ elif model_args.model_name_or_path:
431
+ tokenizer = AutoTokenizer.from_pretrained(
432
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
433
+ )
434
+ else:
435
+ raise ValueError(
436
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
437
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
438
+ )
439
+
440
+ if model_args.model_name_or_path:
441
+ model = FlaxAutoModelForCausalLM.from_pretrained(
442
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
443
+ )
444
+ else:
445
+ model = FlaxAutoModelForCausalLM.from_config(
446
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
447
+ )
448
+
449
+ # Preprocessing the datasets.
450
+ # First we tokenize all the texts.
451
+ if training_args.do_train:
452
+ column_names = dataset["train"].column_names
453
+ else:
454
+ column_names = dataset["validation"].column_names
455
+ text_column_name = "text" if "text" in column_names else column_names[0]
456
+
457
+ # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function
458
+ tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base")
459
+
460
+ def tokenize_function(examples):
461
+ with CaptureLogger(tok_logger) as cl:
462
+ output = tokenizer(examples[text_column_name])
463
+ # clm input could be much much longer than block_size
464
+ if "Token indices sequence length is longer than the" in cl.out:
465
+ tok_logger.warning(
466
+ "^^^^^^^^^^^^^^^^ Please ignore the warning above - this long input will be chunked into smaller bits before being passed to the model."
467
+ )
468
+ return output
469
+
470
+ tokenized_datasets = dataset.map(
471
+ tokenize_function,
472
+ batched=True,
473
+ num_proc=data_args.preprocessing_num_workers,
474
+ remove_columns=column_names,
475
+ load_from_cache_file=not data_args.overwrite_cache,
476
+ )
477
+
478
+ if data_args.block_size is None:
479
+ block_size = tokenizer.model_max_length
480
+ if block_size > config.max_position_embeddings:
481
+ logger.warning(
482
+ f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
483
+ "Picking 1024 instead. You can change that default value by passing --block_size xxx."
484
+ )
485
+ block_size = 1024
486
+ else:
487
+ if data_args.block_size > tokenizer.model_max_length:
488
+ logger.warning(
489
+ f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model"
490
+ f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
491
+ )
492
+ block_size = min(data_args.block_size, tokenizer.model_max_length)
493
+
494
+ # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
495
+ def group_texts(examples):
496
+ # Concatenate all texts.
497
+ concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
498
+ total_length = len(concatenated_examples[list(examples.keys())[0]])
499
+ # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
500
+ # customize this part to your needs.
501
+ if total_length >= block_size:
502
+ total_length = (total_length // block_size) * block_size
503
+ # Split by chunks of max_len.
504
+ result = {
505
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
506
+ for k, t in concatenated_examples.items()
507
+ }
508
+ result["labels"] = result["input_ids"].copy()
509
+ return result
510
+
511
+ # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
512
+ # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
513
+ # to preprocess.
514
+ #
515
+ # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
516
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
517
+
518
+ lm_datasets = tokenized_datasets.map(
519
+ group_texts,
520
+ batched=True,
521
+ num_proc=data_args.preprocessing_num_workers,
522
+ load_from_cache_file=not data_args.overwrite_cache,
523
+ )
524
+
525
+ if training_args.do_train:
526
+ if "train" not in tokenized_datasets:
527
+ raise ValueError("--do_train requires a train dataset")
528
+ train_dataset = lm_datasets["train"]
529
+ if data_args.max_train_samples is not None:
530
+ train_dataset = train_dataset.select(range(data_args.max_train_samples))
531
+
532
+ if training_args.do_eval:
533
+ if "validation" not in tokenized_datasets:
534
+ raise ValueError("--do_eval requires a validation dataset")
535
+ eval_dataset = lm_datasets["validation"]
536
+ if data_args.max_eval_samples is not None:
537
+ eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
538
+
539
+ # Enable tensorboard only on the master node
540
+ has_tensorboard = is_tensorboard_available()
541
+ if has_tensorboard and jax.process_index() == 0:
542
+ try:
543
+ from flax.metrics.tensorboard import SummaryWriter
544
+
545
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
546
+ except ImportError as ie:
547
+ has_tensorboard = False
548
+ logger.warning(
549
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
550
+ )
551
+ else:
552
+ logger.warning(
553
+ "Unable to display metrics through TensorBoard because the package is not installed: "
554
+ "Please run pip install tensorboard to enable."
555
+ )
556
+
557
+ # Initialize our training
558
+ rng = jax.random.PRNGKey(training_args.seed)
559
+ rng, dropout_rng = jax.random.split(rng)
560
+
561
+ # Store some constant
562
+ num_epochs = int(training_args.num_train_epochs)
563
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
564
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
565
+ steps_per_epoch = len(train_dataset) // train_batch_size
566
+ total_train_steps = steps_per_epoch * num_epochs
567
+
568
+ # Create learning rate schedule
569
+ linear_decay_lr_schedule_fn = create_learning_rate_fn(
570
+ len(train_dataset),
571
+ train_batch_size,
572
+ training_args.num_train_epochs,
573
+ training_args.warmup_steps,
574
+ training_args.learning_rate,
575
+ )
576
+
577
+ # We use Optax's "masking" functionality to not apply weight decay
578
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
579
+ # mask boolean with the same structure as the parameters.
580
+ # The mask is True for parameters that should be decayed.
581
+ # Note that this mask is specifically adapted for FlaxGPT2.
582
+ # For other models, one should correct the layer norm parameter naming
583
+ # accordingly.
584
+ def decay_mask_fn(params):
585
+ flat_params = traverse_util.flatten_dict(params)
586
+ flat_mask = {
587
+ path: (path[-1] != "bias" and path[-2:] not in [("ln_1", "scale"), ("ln_2", "scale"), ("ln_f", "scale")])
588
+ for path in flat_params
589
+ }
590
+ return traverse_util.unflatten_dict(flat_mask)
591
+
592
+ # create adam optimizer
593
+ if training_args.adafactor:
594
+ # We use the default parameters here to initialize adafactor,
595
+ # For more details about the parameters please check https://github.com/deepmind/optax/blob/ed02befef9bf81cbbf236be3d2b0e032e9ed4a40/optax/_src/alias.py#L74
596
+ optimizer = optax.adafactor(
597
+ learning_rate=linear_decay_lr_schedule_fn,
598
+ )
599
+ else:
600
+ optimizer = optax.adamw(
601
+ learning_rate=linear_decay_lr_schedule_fn,
602
+ b1=training_args.adam_beta1,
603
+ b2=training_args.adam_beta2,
604
+ eps=training_args.adam_epsilon,
605
+ weight_decay=training_args.weight_decay,
606
+ mask=decay_mask_fn,
607
+ )
608
+
609
+ # Setup train state
610
+ state = TrainState.create(apply_fn=model.__call__, params=model.params, tx=optimizer, dropout_rng=dropout_rng)
611
+
612
+ def loss_fn(logits, labels):
613
+ shift_logits = logits[..., :-1, :]
614
+ shift_labels = labels[..., 1:]
615
+ loss = optax.softmax_cross_entropy(shift_logits, onehot(shift_labels, shift_logits.shape[-1]))
616
+ return loss.mean()
617
+
618
+ # Define gradient update step fn
619
+ def train_step(state, batch):
620
+ dropout_rng, new_dropout_rng = jax.random.split(state.dropout_rng)
621
+
622
+ def compute_loss(params):
623
+ labels = batch.pop("labels")
624
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
625
+ loss = loss_fn(logits, labels)
626
+ return loss
627
+
628
+ grad_fn = jax.value_and_grad(compute_loss)
629
+ loss, grad = grad_fn(state.params)
630
+ grad = jax.lax.pmean(grad, "batch")
631
+
632
+ new_state = state.apply_gradients(grads=grad, dropout_rng=new_dropout_rng)
633
+
634
+ metrics = {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}
635
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
636
+
637
+ return new_state, metrics
638
+
639
+ # Define eval fn
640
+ def eval_step(params, batch):
641
+ labels = batch.pop("labels")
642
+ logits = model(**batch, params=params, train=False)[0]
643
+ loss = loss_fn(logits, labels)
644
+
645
+ # summarize metrics
646
+ metrics = {"loss": loss}
647
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
648
+ return metrics
649
+
650
+ # Create parallel version of the train and eval step
651
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
652
+ p_eval_step = jax.pmap(eval_step, "batch")
653
+
654
+ # Replicate the train state on each device
655
+ state = state.replicate()
656
+
657
+ logger.info("***** Running training *****")
658
+ logger.info(f" Num examples = {len(train_dataset)}")
659
+ logger.info(f" Num Epochs = {num_epochs}")
660
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
661
+ logger.info(f" Total train batch size (w. parallel & distributed) = {train_batch_size}")
662
+ logger.info(f" Total optimization steps = {total_train_steps}")
663
+
664
+ train_time = 0
665
+ train_metrics = []
666
+ epochs = tqdm(range(num_epochs), desc="Epoch ... ", position=0)
667
+ for epoch in epochs:
668
+ # ======================== Training ================================
669
+ train_start = time.time()
670
+
671
+ # Create sampling rng
672
+ rng, input_rng = jax.random.split(rng)
673
+
674
+ # Generate an epoch by shuffling sampling indices from the train dataset
675
+ train_loader = data_loader(input_rng, train_dataset, train_batch_size, shuffle=True)
676
+ steps_per_epoch = len(train_dataset) // train_batch_size
677
+ # train
678
+ for step in tqdm(range(steps_per_epoch), desc="Training...", position=1, leave=False):
679
+ batch = next(train_loader)
680
+ batch = shard(batch)
681
+ state, train_metric = p_train_step(state, batch)
682
+ train_metrics.append(train_metric)
683
+
684
+ cur_step = epoch * (len(train_dataset) // train_batch_size) + step
685
+
686
+ if cur_step % training_args.logging_steps == 0 and cur_step > 0:
687
+ # Save metrics
688
+ train_metric = unreplicate(train_metric)
689
+ train_time += time.time() - train_start
690
+ if has_tensorboard and jax.process_index() == 0:
691
+ write_train_metric(summary_writer, train_metrics, train_time, cur_step)
692
+
693
+ epochs.write(
694
+ f"Step... ({cur_step} | Loss: {train_metric['loss'].mean()}, Learning Rate: {train_metric['learning_rate'].mean()})"
695
+ )
696
+
697
+ train_metrics = []
698
+
699
+ if cur_step % training_args.eval_steps == 0 and cur_step > 0:
700
+ # ======================== Evaluating ==============================
701
+ eval_metrics = []
702
+ eval_loader = data_loader(input_rng, eval_dataset, eval_batch_size)
703
+ eval_steps = len(eval_dataset) // eval_batch_size
704
+ for _ in tqdm(range(eval_steps), desc="Evaluating...", position=2, leave=False):
705
+ # Model forward
706
+ batch = next(eval_loader)
707
+ batch = shard(batch)
708
+ metrics = p_eval_step(state.params, batch)
709
+ eval_metrics.append(metrics)
710
+
711
+ # normalize eval metrics
712
+ eval_metrics = get_metrics(eval_metrics)
713
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
714
+
715
+ try:
716
+ eval_metrics["perplexity"] = math.exp(eval_metrics["loss"])
717
+ except OverflowError:
718
+ eval_metrics["perplexity"] = float("inf")
719
+
720
+ # Print metrics and update progress bar
721
+ desc = f"Step... ({cur_step} | Eval Loss: {eval_metrics['loss']} | Eval Perplexity: {eval_metrics['perplexity']})"
722
+ epochs.write(desc)
723
+ epochs.desc = desc
724
+
725
+ # Save metrics
726
+ if has_tensorboard and jax.process_index() == 0:
727
+ write_eval_metric(summary_writer, eval_metrics, cur_step)
728
+
729
+ if cur_step % training_args.save_steps == 0 and cur_step > 0:
730
+ # save checkpoint after each epoch and push checkpoint to the hub
731
+ if jax.process_index() == 0:
732
+ params = jax.device_get(unreplicate(state.params))
733
+ model.save_pretrained(training_args.output_dir, params=params)
734
+ tokenizer.save_pretrained(training_args.output_dir)
735
+ if training_args.push_to_hub:
736
+ repo.push_to_hub(commit_message=f"Saving weights and logs of step {cur_step}", blocking=False)
737
+
738
+ # Eval after training
739
+ if training_args.do_eval:
740
+ eval_metrics = []
741
+ eval_loader = data_loader(input_rng, eval_dataset, eval_batch_size)
742
+ eval_steps = len(eval_dataset) // eval_batch_size
743
+ for _ in tqdm(range(eval_steps), desc="Evaluating...", position=2, leave=False):
744
+ # Model forward
745
+ batch = shard(next(eval_loader))
746
+ metrics = p_eval_step(state.params, batch)
747
+ eval_metrics.append(metrics)
748
+
749
+ # normalize eval metrics
750
+ eval_metrics = get_metrics(eval_metrics)
751
+ eval_metrics = jax.tree_map(lambda x: jnp.mean(x).item(), eval_metrics)
752
+
753
+ try:
754
+ eval_metrics["perplexity"] = math.exp(eval_metrics["loss"])
755
+ except OverflowError:
756
+ eval_metrics["perplexity"] = float("inf")
757
+
758
+ if jax.process_index() == 0:
759
+ eval_metrics = {f"eval_{metric_name}": value for metric_name, value in eval_metrics.items()}
760
+ path = os.path.join(training_args.output_dir, "eval_results.json")
761
+ with open(path, "w") as f:
762
+ json.dump(eval_metrics, f, indent=4, sort_keys=True)
763
+
764
+
765
+ if __name__ == "__main__":
766
+ main()
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
train_tokenizer.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from tokenizers import trainers, Tokenizer, normalizers, ByteLevelBPETokenizer
3
+
4
+ # load dataset
5
+ dataset = load_dataset("imthanhlv/binhvq_dedup", split="train")
6
+
7
+ # Instantiate tokenizer
8
+ tokenizer = ByteLevelBPETokenizer()
9
+
10
+ def batch_iterator(batch_size=1000):
11
+ for i in range(0, len(dataset), batch_size):
12
+ yield dataset[i: i + batch_size]["text"]
13
+
14
+ # Customized training
15
+ tokenizer.train_from_iterator(batch_iterator(), vocab_size=50257, min_frequency=2, special_tokens=[
16
+ "<s>",
17
+ "<pad>",
18
+ "</s>",
19
+ "<unk>",
20
+ "<mask>",
21
+ ])
22
+
23
+ # Save files to disk
24
+ tokenizer.save("./tokenizer.json")