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