birgermoell commited on
Commit
de02b26
1 Parent(s): e8812de

Updated readme

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