Abinaya Mahendiran commited on
Commit
0675773
1 Parent(s): 070cb25

Added basic scripts and folder structure

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