ydshieh commited on
Commit
a1a9885
1 Parent(s): ae50e80

copy run_summarization_flax.py

Browse files
Files changed (1) hide show
  1. run_summarization_flax.py +821 -0
run_summarization_flax.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Team All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """
17
+ Fine-tuning the library models for summarization.
18
+ """
19
+ # You can also adapt this script on your own sequence to sequence task. Pointers for this are left as comments.
20
+
21
+ import logging
22
+ import os
23
+ import sys
24
+ import time
25
+ from dataclasses import dataclass, field
26
+ from functools import partial
27
+ from pathlib import Path
28
+ from typing import Callable, Optional
29
+
30
+ import datasets
31
+ import nltk # Here to have a nice missing dependency error message early on
32
+ import numpy as np
33
+ from datasets import Dataset, load_dataset, load_metric
34
+ from tqdm import tqdm
35
+
36
+ import jax
37
+ import jax.numpy as jnp
38
+ import optax
39
+ import transformers
40
+ from filelock import FileLock
41
+ from flax import jax_utils, traverse_util
42
+ from flax.jax_utils import unreplicate
43
+ from flax.training import train_state
44
+ from flax.training.common_utils import get_metrics, onehot, shard, shard_prng_key
45
+ from huggingface_hub import Repository
46
+ from transformers import (
47
+ CONFIG_MAPPING,
48
+ FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
49
+ AutoConfig,
50
+ AutoTokenizer,
51
+ FlaxAutoModelForSeq2SeqLM,
52
+ HfArgumentParser,
53
+ TrainingArguments,
54
+ is_tensorboard_available,
55
+ )
56
+ from transformers.file_utils import get_full_repo_name, is_offline_mode
57
+
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+ try:
62
+ nltk.data.find("tokenizers/punkt")
63
+ except (LookupError, OSError):
64
+ if is_offline_mode():
65
+ raise LookupError(
66
+ "Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files"
67
+ )
68
+ with FileLock(".lock") as lock:
69
+ nltk.download("punkt", quiet=True)
70
+
71
+
72
+ MODEL_CONFIG_CLASSES = list(FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.keys())
73
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
74
+
75
+
76
+ @dataclass
77
+ class ModelArguments:
78
+ """
79
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune, or train from scratch.
80
+ """
81
+
82
+ model_name_or_path: Optional[str] = field(
83
+ default=None,
84
+ metadata={
85
+ "help": "The model checkpoint for weights initialization."
86
+ "Don't set if you want to train a model from scratch."
87
+ },
88
+ )
89
+ model_type: Optional[str] = field(
90
+ default=None,
91
+ metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(MODEL_TYPES)},
92
+ )
93
+ config_name: Optional[str] = field(
94
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
95
+ )
96
+ tokenizer_name: Optional[str] = field(
97
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
98
+ )
99
+ cache_dir: Optional[str] = field(
100
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
101
+ )
102
+ use_fast_tokenizer: bool = field(
103
+ default=True,
104
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
105
+ )
106
+ dtype: Optional[str] = field(
107
+ default="float32",
108
+ metadata={
109
+ "help": "Floating-point format in which the model weights should be initialized and trained. Choose one of `[float32, float16, bfloat16]`."
110
+ },
111
+ )
112
+
113
+
114
+ @dataclass
115
+ class DataTrainingArguments:
116
+ """
117
+ Arguments pertaining to what data we are going to input our model for training and eval.
118
+ """
119
+
120
+ dataset_name: Optional[str] = field(
121
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
122
+ )
123
+ dataset_config_name: Optional[str] = field(
124
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
125
+ )
126
+ text_column: Optional[str] = field(
127
+ default=None,
128
+ metadata={"help": "The name of the column in the datasets containing the full texts (for summarization)."},
129
+ )
130
+ summary_column: Optional[str] = field(
131
+ default=None,
132
+ metadata={"help": "The name of the column in the datasets containing the summaries (for summarization)."},
133
+ )
134
+ train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a text file)."})
135
+ validation_file: Optional[str] = field(
136
+ default=None,
137
+ metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."},
138
+ )
139
+ test_file: Optional[str] = field(
140
+ default=None,
141
+ metadata={"help": "An optional input predict data file to do prediction on (a text file)."},
142
+ )
143
+ max_source_length: Optional[int] = field(
144
+ default=1024,
145
+ metadata={
146
+ "help": "The maximum total input sequence length after tokenization. Sequences longer "
147
+ "than this will be truncated, sequences shorter will be padded."
148
+ },
149
+ )
150
+ max_target_length: Optional[int] = field(
151
+ default=128,
152
+ metadata={
153
+ "help": "The maximum total sequence length for target text after tokenization. Sequences longer "
154
+ "than this will be truncated, sequences shorter will be padded."
155
+ },
156
+ )
157
+ val_max_target_length: Optional[int] = field(
158
+ default=None,
159
+ metadata={
160
+ "help": "The maximum total sequence length for validation target text after tokenization. Sequences longer "
161
+ "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`."
162
+ "This argument is also used to override the `max_length` param of `model.generate`, which is used "
163
+ "during evaluation."
164
+ },
165
+ )
166
+ max_train_samples: Optional[int] = field(
167
+ default=None,
168
+ metadata={
169
+ "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
170
+ "value if set."
171
+ },
172
+ )
173
+ max_eval_samples: Optional[int] = field(
174
+ default=None,
175
+ metadata={
176
+ "help": "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
177
+ "value if set."
178
+ },
179
+ )
180
+ max_predict_samples: Optional[int] = field(
181
+ default=None,
182
+ metadata={
183
+ "help": "For debugging purposes or quicker training, truncate the number of prediction examples to this "
184
+ "value if set."
185
+ },
186
+ )
187
+ preprocessing_num_workers: Optional[int] = field(
188
+ default=None,
189
+ metadata={"help": "The number of processes to use for the preprocessing."},
190
+ )
191
+ source_prefix: Optional[str] = field(
192
+ default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."}
193
+ )
194
+ predict_with_generate: bool = field(
195
+ default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."}
196
+ )
197
+ num_beams: Optional[int] = field(
198
+ default=None,
199
+ metadata={
200
+ "help": "Number of beams to use for evaluation. This argument will be passed to `model.generate`, "
201
+ "which is used during evaluation."
202
+ },
203
+ )
204
+ overwrite_cache: bool = field(
205
+ default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
206
+ )
207
+
208
+ def __post_init__(self):
209
+ if self.dataset_name is None and self.train_file is None and self.validation_file is None:
210
+ raise ValueError("Need either a dataset name or a training/validation file.")
211
+ else:
212
+ if self.train_file is not None:
213
+ extension = self.train_file.split(".")[-1]
214
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
215
+ if self.validation_file is not None:
216
+ extension = self.validation_file.split(".")[-1]
217
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
218
+ if self.val_max_target_length is None:
219
+ self.val_max_target_length = self.max_target_length
220
+
221
+
222
+ summarization_name_mapping = {
223
+ "amazon_reviews_multi": ("review_body", "review_title"),
224
+ "big_patent": ("description", "abstract"),
225
+ "cnn_dailymail": ("article", "highlights"),
226
+ "orange_sum": ("text", "summary"),
227
+ "pn_summary": ("article", "summary"),
228
+ "psc": ("extract_text", "summary_text"),
229
+ "samsum": ("dialogue", "summary"),
230
+ "thaisum": ("body", "summary"),
231
+ "xglue": ("news_body", "news_title"),
232
+ "xsum": ("document", "summary"),
233
+ "wiki_summary": ("article", "highlights"),
234
+ }
235
+
236
+
237
+ class TrainState(train_state.TrainState):
238
+ dropout_rng: jnp.ndarray
239
+
240
+ def replicate(self):
241
+ return jax_utils.replicate(self).replace(dropout_rng=shard_prng_key(self.dropout_rng))
242
+
243
+
244
+ def data_loader(rng: jax.random.PRNGKey, dataset: Dataset, batch_size: int, shuffle: bool = False):
245
+ """
246
+ Returns batches of size `batch_size` from truncated `dataset`, sharded over all local devices.
247
+ Shuffle batches if `shuffle` is `True`.
248
+ """
249
+ steps_per_epoch = len(dataset) // batch_size
250
+
251
+ if shuffle:
252
+ batch_idx = jax.random.permutation(rng, len(dataset))
253
+ else:
254
+ batch_idx = jnp.arange(len(dataset))
255
+
256
+ batch_idx = batch_idx[: steps_per_epoch * batch_size] # Skip incomplete batch.
257
+ batch_idx = batch_idx.reshape((steps_per_epoch, batch_size))
258
+
259
+ for idx in batch_idx:
260
+ batch = dataset[idx]
261
+ batch = {k: jnp.array(v) for k, v in batch.items()}
262
+
263
+ batch = shard(batch)
264
+
265
+ yield batch
266
+
267
+
268
+ def write_metric(summary_writer, train_metrics, eval_metrics, train_time, step):
269
+ summary_writer.scalar("train_time", train_time, step)
270
+
271
+ train_metrics = get_metrics(train_metrics)
272
+ for key, vals in train_metrics.items():
273
+ tag = f"train_{key}"
274
+ for i, val in enumerate(vals):
275
+ summary_writer.scalar(tag, val, step - len(vals) + i + 1)
276
+
277
+ for metric_name, value in eval_metrics.items():
278
+ summary_writer.scalar(f"eval_{metric_name}", value, step)
279
+
280
+
281
+ def create_learning_rate_fn(
282
+ train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float
283
+ ) -> Callable[[int], jnp.array]:
284
+ """Returns a linear warmup, linear_decay learning rate function."""
285
+ steps_per_epoch = train_ds_size // train_batch_size
286
+ num_train_steps = steps_per_epoch * num_train_epochs
287
+ warmup_fn = optax.linear_schedule(init_value=0.0, end_value=learning_rate, transition_steps=num_warmup_steps)
288
+ decay_fn = optax.linear_schedule(
289
+ init_value=learning_rate, end_value=0, transition_steps=num_train_steps - num_warmup_steps
290
+ )
291
+ schedule_fn = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[num_warmup_steps])
292
+ return schedule_fn
293
+
294
+
295
+ def main():
296
+ # See all possible arguments in src/transformers/training_args.py
297
+ # or by passing the --help flag to this script.
298
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
299
+
300
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
301
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
302
+ # If we pass only one argument to the script and it's the path to a json file,
303
+ # let's parse it to get our arguments.
304
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
305
+ else:
306
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
307
+
308
+ if (
309
+ os.path.exists(training_args.output_dir)
310
+ and os.listdir(training_args.output_dir)
311
+ and training_args.do_train
312
+ and not training_args.overwrite_output_dir
313
+ ):
314
+ raise ValueError(
315
+ f"Output directory ({training_args.output_dir}) already exists and is not empty."
316
+ "Use --overwrite_output_dir to overcome."
317
+ )
318
+
319
+ # Make one log on every process with the configuration for debugging.
320
+ logging.basicConfig(
321
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
322
+ datefmt="%m/%d/%Y %H:%M:%S",
323
+ level=logging.INFO,
324
+ )
325
+ # Setup logging, we only want one process per machine to log things on the screen.
326
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
327
+ if jax.process_index() == 0:
328
+ datasets.utils.logging.set_verbosity_warning()
329
+ transformers.utils.logging.set_verbosity_info()
330
+ else:
331
+ datasets.utils.logging.set_verbosity_error()
332
+ transformers.utils.logging.set_verbosity_error()
333
+
334
+ # Set the verbosity to info of the Transformers logger (on main process only):
335
+ logger.info(f"Training/evaluation parameters {training_args}")
336
+
337
+ # Handle the repository creation
338
+ if training_args.push_to_hub:
339
+ if training_args.hub_model_id is None:
340
+ repo_name = get_full_repo_name(
341
+ Path(training_args.output_dir).absolute().name, token=training_args.hub_token
342
+ )
343
+ else:
344
+ repo_name = training_args.hub_model_id
345
+ repo = Repository(training_args.output_dir, clone_from=repo_name)
346
+
347
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
348
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
349
+ # (the dataset will be downloaded automatically from the datasets Hub).
350
+ #
351
+ # For CSV/JSON files this script will use the first column for the full texts and the second column for the
352
+ # summaries (unless you specify column names for this with the `text_column` and `summary_column` arguments).
353
+ #
354
+ if data_args.dataset_name is not None:
355
+ # Downloading and loading a dataset from the hub.
356
+ dataset = load_dataset(
357
+ data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, keep_in_memory=False
358
+ )
359
+ else:
360
+ data_files = {}
361
+ if data_args.train_file is not None:
362
+ data_files["train"] = data_args.train_file
363
+ extension = data_args.train_file.split(".")[-1]
364
+ if data_args.validation_file is not None:
365
+ data_files["validation"] = data_args.validation_file
366
+ extension = data_args.validation_file.split(".")[-1]
367
+ if data_args.test_file is not None:
368
+ data_files["test"] = data_args.test_file
369
+ extension = data_args.test_file.split(".")[-1]
370
+ dataset = load_dataset(extension, data_files=data_files, cache_dir=model_args.cache_dir)
371
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
372
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
373
+
374
+ # Load pretrained model and tokenizer
375
+
376
+ if model_args.config_name:
377
+ config = AutoConfig.from_pretrained(model_args.config_name, cache_dir=model_args.cache_dir)
378
+ elif model_args.model_name_or_path:
379
+ config = AutoConfig.from_pretrained(model_args.model_name_or_path, cache_dir=model_args.cache_dir)
380
+ else:
381
+ config = CONFIG_MAPPING[model_args.model_type]()
382
+ logger.warning("You are instantiating a new config instance from scratch.")
383
+
384
+ if model_args.tokenizer_name:
385
+ tokenizer = AutoTokenizer.from_pretrained(
386
+ model_args.tokenizer_name, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
387
+ )
388
+ elif model_args.model_name_or_path:
389
+ tokenizer = AutoTokenizer.from_pretrained(
390
+ model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer
391
+ )
392
+ else:
393
+ raise ValueError(
394
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
395
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
396
+ )
397
+
398
+ if model_args.model_name_or_path:
399
+ model = FlaxAutoModelForSeq2SeqLM.from_pretrained(
400
+ model_args.model_name_or_path, config=config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
401
+ )
402
+ else:
403
+ model = FlaxAutoModelForSeq2SeqLM.from_config(
404
+ config, seed=training_args.seed, dtype=getattr(jnp, model_args.dtype)
405
+ )
406
+
407
+ if model.config.decoder_start_token_id is None:
408
+ raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined")
409
+
410
+ prefix = data_args.source_prefix if data_args.source_prefix is not None else ""
411
+
412
+ # Preprocessing the datasets.
413
+ # We need to tokenize inputs and targets.
414
+ if training_args.do_train:
415
+ column_names = dataset["train"].column_names
416
+ elif training_args.do_eval:
417
+ column_names = dataset["validation"].column_names
418
+ elif training_args.do_predict:
419
+ column_names = dataset["test"].column_names
420
+ else:
421
+ logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.")
422
+ return
423
+
424
+ # Get the column names for input/target.
425
+ dataset_columns = summarization_name_mapping.get(data_args.dataset_name, None)
426
+ if data_args.text_column is None:
427
+ text_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
428
+ else:
429
+ text_column = data_args.text_column
430
+ if text_column not in column_names:
431
+ raise ValueError(
432
+ f"--text_column' value '{data_args.text_column}' needs to be one of: {', '.join(column_names)}"
433
+ )
434
+ if data_args.summary_column is None:
435
+ summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
436
+ else:
437
+ summary_column = data_args.summary_column
438
+ if summary_column not in column_names:
439
+ raise ValueError(
440
+ f"--summary_column' value '{data_args.summary_column}' needs to be one of: {', '.join(column_names)}"
441
+ )
442
+
443
+ # Temporarily set max_target_length for training.
444
+ max_target_length = data_args.max_target_length
445
+
446
+ # In Flax, for seq2seq models we need to pass `decoder_input_ids`
447
+ # as the Flax models don't accept `labels`, we need to prepare the decoder_input_ids here
448
+ # for that dynamically import the `shift_tokens_right` function from the model file
449
+ model_module = __import__(model.__module__, fromlist=["shift_tokens_tight"])
450
+ shift_tokens_right_fn = getattr(model_module, "shift_tokens_right")
451
+
452
+ # Setting padding="max_length" as we need fixed length inputs for jitted functions
453
+ def preprocess_function(examples):
454
+ inputs = examples[text_column]
455
+ targets = examples[summary_column]
456
+ inputs = [prefix + inp for inp in inputs]
457
+ model_inputs = tokenizer(
458
+ inputs, max_length=data_args.max_source_length, padding="max_length", truncation=True, return_tensors="np"
459
+ )
460
+
461
+ # Setup the tokenizer for targets
462
+ with tokenizer.as_target_tokenizer():
463
+ labels = tokenizer(
464
+ targets, max_length=max_target_length, padding="max_length", truncation=True, return_tensors="np"
465
+ )
466
+
467
+ model_inputs["labels"] = labels["input_ids"]
468
+ decoder_input_ids = shift_tokens_right_fn(
469
+ jnp.array(labels["input_ids"]), config.pad_token_id, config.decoder_start_token_id
470
+ )
471
+ model_inputs["decoder_input_ids"] = np.asarray(decoder_input_ids)
472
+
473
+ # We need decoder_attention_mask so we can ignore pad tokens from loss
474
+ model_inputs["decoder_attention_mask"] = labels["attention_mask"]
475
+
476
+ return model_inputs
477
+
478
+ if training_args.do_train:
479
+ if "train" not in dataset:
480
+ raise ValueError("--do_train requires a train dataset")
481
+ train_dataset = dataset["train"]
482
+ if data_args.max_train_samples is not None:
483
+ train_dataset = train_dataset.select(range(data_args.max_train_samples))
484
+ train_dataset = train_dataset.map(
485
+ preprocess_function,
486
+ batched=True,
487
+ num_proc=data_args.preprocessing_num_workers,
488
+ remove_columns=column_names,
489
+ load_from_cache_file=not data_args.overwrite_cache,
490
+ desc="Running tokenizer on train dataset",
491
+ )
492
+
493
+ if training_args.do_eval:
494
+ max_target_length = data_args.val_max_target_length
495
+ if "validation" not in dataset:
496
+ raise ValueError("--do_eval requires a validation dataset")
497
+ eval_dataset = dataset["validation"]
498
+ if data_args.max_eval_samples is not None:
499
+ eval_dataset = eval_dataset.select(range(data_args.max_eval_samples))
500
+ eval_dataset = eval_dataset.map(
501
+ preprocess_function,
502
+ batched=True,
503
+ num_proc=data_args.preprocessing_num_workers,
504
+ remove_columns=column_names,
505
+ load_from_cache_file=not data_args.overwrite_cache,
506
+ desc="Running tokenizer on validation dataset",
507
+ )
508
+
509
+ if training_args.do_predict:
510
+ max_target_length = data_args.val_max_target_length
511
+ if "test" not in dataset:
512
+ raise ValueError("--do_predict requires a test dataset")
513
+ predict_dataset = dataset["test"]
514
+ if data_args.max_predict_samples is not None:
515
+ predict_dataset = predict_dataset.select(range(data_args.max_predict_samples))
516
+ predict_dataset = predict_dataset.map(
517
+ preprocess_function,
518
+ batched=True,
519
+ num_proc=data_args.preprocessing_num_workers,
520
+ remove_columns=column_names,
521
+ load_from_cache_file=not data_args.overwrite_cache,
522
+ desc="Running tokenizer on prediction dataset",
523
+ )
524
+
525
+ # Metric
526
+ metric = load_metric("rouge")
527
+
528
+ def postprocess_text(preds, labels):
529
+ preds = [pred.strip() for pred in preds]
530
+ labels = [label.strip() for label in labels]
531
+
532
+ # rougeLSum expects newline after each sentence
533
+ preds = ["\n".join(nltk.sent_tokenize(pred)) for pred in preds]
534
+ labels = ["\n".join(nltk.sent_tokenize(label)) for label in labels]
535
+
536
+ return preds, labels
537
+
538
+ def compute_metrics(preds, labels):
539
+ decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
540
+ decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
541
+
542
+ # Some simple post-processing
543
+ decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels)
544
+
545
+ result = metric.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)
546
+ # Extract a few results from ROUGE
547
+ result = {key: value.mid.fmeasure * 100 for key, value in result.items()}
548
+
549
+ prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds]
550
+ result["gen_len"] = np.mean(prediction_lens)
551
+ result = {k: round(v, 4) for k, v in result.items()}
552
+ return result
553
+
554
+ # Enable tensorboard only on the master node
555
+ has_tensorboard = is_tensorboard_available()
556
+ if has_tensorboard and jax.process_index() == 0:
557
+ try:
558
+ from flax.metrics.tensorboard import SummaryWriter
559
+
560
+ summary_writer = SummaryWriter(log_dir=Path(training_args.output_dir))
561
+ except ImportError as ie:
562
+ has_tensorboard = False
563
+ logger.warning(
564
+ f"Unable to display metrics through TensorBoard because some package are not installed: {ie}"
565
+ )
566
+ else:
567
+ logger.warning(
568
+ "Unable to display metrics through TensorBoard because the package is not installed: "
569
+ "Please run pip install tensorboard to enable."
570
+ )
571
+
572
+ # Initialize our training
573
+ rng = jax.random.PRNGKey(training_args.seed)
574
+ rng, dropout_rng = jax.random.split(rng)
575
+
576
+ # Store some constant
577
+ num_epochs = int(training_args.num_train_epochs)
578
+ train_batch_size = int(training_args.per_device_train_batch_size) * jax.device_count()
579
+ eval_batch_size = int(training_args.per_device_eval_batch_size) * jax.device_count()
580
+ steps_per_epoch = len(train_dataset) // train_batch_size
581
+ total_train_steps = steps_per_epoch * num_epochs
582
+
583
+ # Create learning rate schedule
584
+ linear_decay_lr_schedule_fn = create_learning_rate_fn(
585
+ len(train_dataset),
586
+ train_batch_size,
587
+ training_args.num_train_epochs,
588
+ training_args.warmup_steps,
589
+ training_args.learning_rate,
590
+ )
591
+
592
+ # We use Optax's "masking" functionality to not apply weight decay
593
+ # to bias and LayerNorm scale parameters. decay_mask_fn returns a
594
+ # mask boolean with the same structure as the parameters.
595
+ # The mask is True for parameters that should be decayed.
596
+ # Note that this mask is specifically adapted for FlaxBart.
597
+ # For FlaxT5, one should correct the layer norm parameter naming
598
+ # accordingly - see `run_t5_mlm_flax.py` e.g.
599
+ def decay_mask_fn(params):
600
+ flat_params = traverse_util.flatten_dict(params)
601
+ layer_norm_params = [
602
+ (name, "scale") for name in ["self_attn_layer_norm", "layernorm_embedding", "final_layer_norm"]
603
+ ]
604
+ flat_mask = {path: (path[-1] != "bias" and path[-2:] not in layer_norm_params) for path in flat_params}
605
+ return traverse_util.unflatten_dict(flat_mask)
606
+
607
+ # create adam optimizer
608
+ adamw = optax.adamw(
609
+ learning_rate=linear_decay_lr_schedule_fn,
610
+ b1=training_args.adam_beta1,
611
+ b2=training_args.adam_beta2,
612
+ eps=training_args.adam_epsilon,
613
+ weight_decay=training_args.weight_decay,
614
+ mask=decay_mask_fn,
615
+ )
616
+
617
+ # Setup train state
618
+ state = TrainState.create(apply_fn=model.__call__, params=model.params, tx=adamw, dropout_rng=dropout_rng)
619
+
620
+ # label smoothed cross entropy
621
+ def loss_fn(logits, labels, padding_mask, label_smoothing_factor=0.0):
622
+ """
623
+ The label smoothing implementation is adapted from Flax's official example:
624
+ https://github.com/google/flax/blob/87a211135c6a377c8f29048a1cac3840e38b9da4/examples/wmt/train.py#L104
625
+ """
626
+ vocab_size = logits.shape[-1]
627
+ confidence = 1.0 - label_smoothing_factor
628
+ low_confidence = (1.0 - confidence) / (vocab_size - 1)
629
+ normalizing_constant = -(
630
+ confidence * jnp.log(confidence) + (vocab_size - 1) * low_confidence * jnp.log(low_confidence + 1e-20)
631
+ )
632
+ soft_labels = onehot(labels, vocab_size, on_value=confidence, off_value=low_confidence)
633
+
634
+ loss = optax.softmax_cross_entropy(logits, soft_labels)
635
+ loss = loss - normalizing_constant
636
+
637
+ # ignore padded tokens from loss
638
+ loss = loss * padding_mask
639
+ loss = loss.sum() / padding_mask.sum()
640
+ return loss
641
+
642
+ # Define gradient update step fn
643
+ def train_step(state, batch, label_smoothing_factor=0.0):
644
+ dropout_rng, new_dropout_rng = jax.random.split(state.dropout_rng)
645
+
646
+ def compute_loss(params):
647
+ labels = batch.pop("labels")
648
+ logits = state.apply_fn(**batch, params=params, dropout_rng=dropout_rng, train=True)[0]
649
+ loss = loss_fn(logits, labels, batch["decoder_attention_mask"], label_smoothing_factor)
650
+ return loss
651
+
652
+ grad_fn = jax.value_and_grad(compute_loss)
653
+ loss, grad = grad_fn(state.params)
654
+ grad = jax.lax.pmean(grad, "batch")
655
+
656
+ new_state = state.apply_gradients(grads=grad, dropout_rng=new_dropout_rng)
657
+
658
+ metrics = {"loss": loss, "learning_rate": linear_decay_lr_schedule_fn(state.step)}
659
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
660
+
661
+ return new_state, metrics
662
+
663
+ # Define eval fn
664
+ def eval_step(params, batch, label_smoothing_factor=0.0):
665
+ labels = batch.pop("labels")
666
+ logits = model(**batch, params=params, train=False)[0]
667
+ loss = loss_fn(logits, labels, batch["decoder_attention_mask"], label_smoothing_factor)
668
+
669
+ # summarize metrics
670
+ metrics = {"loss": loss}
671
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
672
+ return metrics
673
+
674
+ # Define generation function
675
+ max_length = (
676
+ data_args.val_max_target_length if data_args.val_max_target_length is not None else model.config.max_length
677
+ )
678
+ num_beams = data_args.num_beams if data_args.num_beams is not None else model.config.num_beams
679
+ gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
680
+
681
+ def generate_step(params, batch):
682
+ model.params = params
683
+ output_ids = model.generate(batch["input_ids"], attention_mask=batch["attention_mask"], **gen_kwargs)
684
+ return output_ids.sequences
685
+
686
+ # Create parallel version of the train and eval step
687
+ p_train_step = jax.pmap(
688
+ partial(train_step, label_smoothing_factor=training_args.label_smoothing_factor), "batch", donate_argnums=(0,)
689
+ )
690
+ p_eval_step = jax.pmap(partial(eval_step, label_smoothing_factor=training_args.label_smoothing_factor), "batch")
691
+ p_generate_step = jax.pmap(generate_step, "batch")
692
+
693
+ # Replicate the train state on each device
694
+ state = state.replicate()
695
+
696
+ logger.info("***** Running training *****")
697
+ logger.info(f" Num examples = {len(train_dataset)}")
698
+ logger.info(f" Num Epochs = {num_epochs}")
699
+ logger.info(f" Instantaneous batch size per device = {training_args.per_device_train_batch_size}")
700
+ logger.info(f" Total train batch size (w. parallel & distributed) = {train_batch_size}")
701
+ logger.info(f" Total optimization steps = {total_train_steps}")
702
+
703
+ train_time = 0
704
+ epochs = tqdm(range(num_epochs), desc=f"Epoch ... (1/{num_epochs})", position=0)
705
+ for epoch in epochs:
706
+ # ======================== Training ================================
707
+ train_start = time.time()
708
+
709
+ # Create sampling rng
710
+ rng, input_rng = jax.random.split(rng)
711
+ train_metrics = []
712
+
713
+ # Generate an epoch by shuffling sampling indices from the train dataset
714
+ train_loader = data_loader(input_rng, train_dataset, train_batch_size, shuffle=True)
715
+ steps_per_epoch = len(train_dataset) // train_batch_size
716
+ # train
717
+ for _ in tqdm(range(steps_per_epoch), desc="Training...", position=1, leave=False):
718
+ batch = next(train_loader)
719
+ state, train_metric = p_train_step(state, batch)
720
+ train_metrics.append(train_metric)
721
+
722
+ train_time += time.time() - train_start
723
+
724
+ train_metric = unreplicate(train_metric)
725
+
726
+ epochs.write(
727
+ f"Epoch... ({epoch + 1}/{num_epochs} | Loss: {train_metric['loss']}, Learning Rate: {train_metric['learning_rate']})"
728
+ )
729
+
730
+ # ======================== Evaluating ==============================
731
+ eval_metrics = []
732
+ eval_preds = []
733
+ eval_labels = []
734
+
735
+ eval_loader = data_loader(input_rng, eval_dataset, eval_batch_size)
736
+ eval_steps = len(eval_dataset) // eval_batch_size
737
+ for _ in tqdm(range(eval_steps), desc="Evaluating...", position=2, leave=False):
738
+ # Model forward
739
+ batch = next(eval_loader)
740
+ labels = batch["labels"]
741
+
742
+ metrics = p_eval_step(state.params, batch)
743
+ eval_metrics.append(metrics)
744
+
745
+ # generation
746
+ if data_args.predict_with_generate:
747
+ generated_ids = p_generate_step(state.params, batch)
748
+ eval_preds.extend(jax.device_get(generated_ids.reshape(-1, gen_kwargs["max_length"])))
749
+ eval_labels.extend(jax.device_get(labels.reshape(-1, labels.shape[-1])))
750
+
751
+ # normalize eval metrics
752
+ eval_metrics = get_metrics(eval_metrics)
753
+ eval_metrics = jax.tree_map(jnp.mean, eval_metrics)
754
+
755
+ # compute ROUGE metrics
756
+ rouge_desc = ""
757
+ if data_args.predict_with_generate:
758
+ rouge_metrics = compute_metrics(eval_preds, eval_labels)
759
+ eval_metrics.update(rouge_metrics)
760
+ rouge_desc = " ".join([f"Eval {key}: {value} |" for key, value in rouge_metrics.items()])
761
+
762
+ # Print metrics and update progress bar
763
+ desc = f"Epoch... ({epoch + 1}/{num_epochs} | Eval Loss: {eval_metrics['loss']} | {rouge_desc})"
764
+ epochs.write(desc)
765
+ epochs.desc = desc
766
+
767
+ # Save metrics
768
+ if has_tensorboard and jax.process_index() == 0:
769
+ cur_step = epoch * (len(train_dataset) // train_batch_size)
770
+ write_metric(summary_writer, train_metrics, eval_metrics, train_time, cur_step)
771
+
772
+ # ======================== Prediction loop ==============================
773
+ if training_args.do_predict:
774
+ logger.info("*** Predict ***")
775
+
776
+ pred_metrics = []
777
+ pred_generations = []
778
+ pred_labels = []
779
+
780
+ pred_loader = data_loader(input_rng, predict_dataset, eval_batch_size)
781
+ pred_steps = len(predict_dataset) // eval_batch_size
782
+ for _ in tqdm(range(pred_steps), desc="Predicting...", position=2, leave=False):
783
+ # Model forward
784
+ batch = next(pred_loader)
785
+ labels = batch["labels"]
786
+
787
+ metrics = p_eval_step(state.params, batch)
788
+ pred_metrics.append(metrics)
789
+
790
+ # generation
791
+ if data_args.predict_with_generate:
792
+ generated_ids = p_generate_step(state.params, batch)
793
+ pred_generations.extend(jax.device_get(generated_ids.reshape(-1, gen_kwargs["max_length"])))
794
+ pred_labels.extend(jax.device_get(labels.reshape(-1, labels.shape[-1])))
795
+
796
+ # normalize prediction metrics
797
+ pred_metrics = get_metrics(pred_metrics)
798
+ pred_metrics = jax.tree_map(jnp.mean, pred_metrics)
799
+
800
+ # compute ROUGE metrics
801
+ rouge_desc = ""
802
+ if data_args.predict_with_generate:
803
+ rouge_metrics = compute_metrics(pred_generations, pred_labels)
804
+ pred_metrics.update(rouge_metrics)
805
+ rouge_desc = " ".join([f"Predict {key}: {value} |" for key, value in rouge_metrics.items()])
806
+
807
+ # Print metrics
808
+ desc = f"Predict Loss: {pred_metrics['loss']} | {rouge_desc})"
809
+ logger.info(desc)
810
+
811
+ # save checkpoint after each epoch and push checkpoint to the hub
812
+ if jax.process_index() == 0:
813
+ params = jax.device_get(jax.tree_map(lambda x: x[0], state.params))
814
+ model.save_pretrained(training_args.output_dir, params=params)
815
+ tokenizer.save_pretrained(training_args.output_dir)
816
+ if training_args.push_to_hub:
817
+ repo.push_to_hub(commit_message=f"Saving weights and logs of epoch {epoch}", blocking=False)
818
+
819
+
820
+ if __name__ == "__main__":
821
+ main()