-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
381 lines (263 loc) · 16.6 KB
/
train.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# -*- coding: utf-8 -*-
"""Copy of Summarization
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Umr2wMl5tRGfpv1lphvtjJ-1ROPYmtPq
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers and 🤗 Datasets as well as other dependencies. Uncomment the following cell and run it.
"""
"""If you're opening this notebook locally, make sure your environment has an install from the last version of those libraries.
To be able to share your model with the community and generate results like the one shown in the picture below via the inference API, there are a few more steps to follow.
First you have to store your authentication token from the Hugging Face website (sign up [here](https://huggingface.co/join) if you haven't already!) then execute the following cell and input your username and password:
"""
# from huggingface_hub import notebook_login
# notebook_login()
"""Then you need to install Git-LFS. Uncomment the following instructions:"""
# !apt install git-lfs
"""Make sure your version of Transformers is at least 4.11.0 since the functionality was introduced in that version:"""
import transformers
print(transformers.__version__)
"""You can find a script version of this notebook to fine-tune your model in a distributed fashion using multiple GPUs or TPUs [here](https://github.com/huggingface/transformers/tree/master/examples/seq2seq).
We also quickly upload some telemetry - this tells us which examples and software versions are getting used so we know where to prioritize our maintenance efforts. We don't collect (or care about) any personally identifiable information, but if you'd prefer not to be counted, feel free to skip this step or delete this cell entirely.
"""
from transformers.utils import send_example_telemetry
send_example_telemetry("summarization_notebook", framework="pytorch")
"""# Fine-tuning a model on a summarization task
In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model for a summarization task. We will use the [XSum dataset](https://arxiv.org/pdf/1808.08745.pdf) (for extreme summarization) which contains BBC articles accompanied with single-sentence summaries.
![Widget inference on a summarization task](https://github.com/huggingface/notebooks/blob/main/examples/images/summarization.png?raw=1)
We will see how to easily load the dataset for this task using 🤗 Datasets and how to fine-tune a model on it using the `Trainer` API.
"""
model_checkpoint = "t5-base"
"""This notebook is built to run with any model checkpoint from the [Model Hub](https://huggingface.co/models) as long as that model has a sequence-to-sequence version in the Transformers library. Here we picked the [`t5-small`](https://huggingface.co/t5-small) checkpoint.
## Loading the dataset
We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data and get the metric we need to use for evaluation (to compare our model to the benchmark). This can be easily done with the functions `load_dataset` and `load_metric`.
"""
from datasets import load_dataset, load_metric
import os
import config
# data_dir = os.path.abspath(os.getcwd())
data_dir = str(config.DATA_ROOT)
# import pdb; pdb.set_trace()
data_files = {"train": "train.json", "test": "test.json"}
raw_datasets = load_dataset(
data_dir,
data_files=data_files,
)
#######################################################################
metric = load_metric("rouge")
"""The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasetdict), which contains one key for the training, validation and test set:
To access an actual element, you need to select a split first, then give an index:
To get a sense of what the data looks like, the following function will show some examples picked randomly in the dataset.
"""
import datasets
import random
import pandas as pd
# from IPython.display import display, HTML
def show_random_elements(dataset, num_examples=5):
assert num_examples <= len(
dataset
), "Can't pick more elements than there are in the dataset."
picks = []
for _ in range(num_examples):
pick = random.randint(0, len(dataset) - 1)
while pick in picks:
pick = random.randint(0, len(dataset) - 1)
picks.append(pick)
df = pd.DataFrame(dataset[picks])
for column, typ in dataset.features.items():
if isinstance(typ, datasets.ClassLabel):
df[column] = df[column].transform(lambda i: typ.names[i])
display(HTML(df.to_html()))
# show_random_elements(raw_datasets["train"])
"""The metric is an instance of [`datasets.Metric`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Metric):"""
# metric
"""You can call its `compute` method with your predictions and labels, which need to be list of decoded strings:"""
fake_preds = ["hello there", "general kenobi"]
fake_labels = ["hello there", "general kenobi"]
metric.compute(predictions=fake_preds, references=fake_labels)
"""## Preprocessing the data
Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model expects, as well as generate the other inputs that the model requires.
To do all of this, we instantiate our tokenizer with the `AutoTokenizer.from_pretrained` method, which will ensure:
- we get a tokenizer that corresponds to the model architecture we want to use,
- we download the vocabulary used when pretraining this specific checkpoint.
That vocabulary will be cached, so it's not downloaded again the next time we run the cell.
"""
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
"""By default, the call above will use one of the fast tokenizers (backed by Rust) from the 🤗 Tokenizers library.
You can directly call this tokenizer on one sentence or a pair of sentences:
"""
print(
tokenizer(
"politik <extra_id_0> sich stellen <extra_id_1> scheinen <extra_id_2> stimmen <extra_id_3>"
)
)
"""Depending on the model you selected, you will see different keys in the dictionary returned by the cell above. They don't matter much for what we're doing here (just know they are required by the model we will instantiate later), you can learn more about them in [this tutorial](https://huggingface.co/transformers/preprocessing.html) if you're interested.
Instead of one sentence, we can pass along a list of sentences:
"""
# tokenizer(["Hello, this one sentence!", "This is another sentence."])
"""To prepare the targets for our model, we need to tokenize them inside the `as_target_tokenizer` context manager. This will make sure the tokenizer uses the special tokens corresponding to the targets:"""
with tokenizer.as_target_tokenizer():
print(
tokenizer(
[
'wirtschaft <extra_id_0> steigen <extra_id_1> machen <extra_id_2> sagen <extra_id_3> Die Verbraucherpreise stiegen im M\u00e4rz weiter stark um 5,4 Prozent im Vergleich zum Vorjahreszeitraum. Die Erzeugerpreise legten im vergangenen Monat sogar um 7,3 Prozent zu. "Die nationale Wirtschaft hat einen guten Start mit best\u00e4ndigem und relativ schnellem Wachstum gemacht", sagte ein Sprecher des Statistikamts in Peking. Die chinesische Wirtschaft wuchs im vergangenen Jahr sogar noch um 10,3 Prozent, doch will die Regierung das Wachstum wegen der hohen Inflation und der Immobilienblase bremsen. <extra_id_4>'
]
)
)
# import pdb; pdb.set_trace()
"""If you are using one of the five T5 checkpoints we have to prefix the inputs with "summarize:" (the model can also translate and it needs the prefix to know which task it has to perform)."""
if model_checkpoint in ["t5-small", "t5-base", "t5-larg", "t5-3b", "t5-11b"]:
prefix = ""
else:
prefix = ""
"""We can then write the function that will preprocess our samples. We just feed them to the `tokenizer` with the argument `truncation=True`. This will ensure that an input longer that what the model selected can handle will be truncated to the maximum length accepted by the model. The padding will be dealt with later on (in a data collator) so we pad examples to the longest length in the batch and not the whole dataset."""
max_input_length = 56
max_target_length = 256
def preprocess_function(examples):
inputs = [prefix + doc for doc in examples["document"]]
model_inputs = tokenizer(inputs, max_length=max_input_length, truncation=True)
# Setup the tokenizer for targets
with tokenizer.as_target_tokenizer():
labels = tokenizer(
examples["summary"], max_length=max_target_length, truncation=True
)
model_inputs["labels"] = labels["input_ids"]
return model_inputs
"""This function works with one or several examples. In the case of several examples, the tokenizer will return a list of lists for each key:"""
preprocess_function(raw_datasets["train"][:2])
"""To apply this function on all the pairs of sentences in our dataset, we just use the `map` method of our `dataset` object we created earlier. This will apply the function on all the elements of all the splits in `dataset`, so our training, validation and testing data will be preprocessed in one single command."""
tokenized_datasets = raw_datasets.map(preprocess_function, batched=True)
"""Even better, the results are automatically cached by the 🤗 Datasets library to avoid spending time on this step the next time you run your notebook. The 🤗 Datasets library is normally smart enough to detect when the function you pass to map has changed (and thus requires to not use the cache data). For instance, it will properly detect if you change the task in the first cell and rerun the notebook. 🤗 Datasets warns you when it uses cached files, you can pass `load_from_cache_file=False` in the call to `map` to not use the cached files and force the preprocessing to be applied again.
Note that we passed `batched=True` to encode the texts by batches together. This is to leverage the full benefit of the fast tokenizer we loaded earlier, which will use multi-threading to treat the texts in a batch concurrently.
## Fine-tuning the model
Now that our data is ready, we can download the pretrained model and fine-tune it. Since our task is of the sequence-to-sequence kind, we use the `AutoModelForSeq2SeqLM` class. Like with the tokenizer, the `from_pretrained` method will download and cache the model for us.
"""
from transformers import (
AutoModelForSeq2SeqLM,
DataCollatorForSeq2Seq,
Seq2SeqTrainingArguments,
Seq2SeqTrainer,
)
model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint)
"""Note that we don't get a warning like in our classification example. This means we used all the weights of the pretrained model and there is no randomly initialized head in this case.
To instantiate a `Seq2SeqTrainer`, we will need to define three more things. The most important is the [`Seq2SeqTrainingArguments`](https://huggingface.co/transformers/main_classes/trainer.html#transformers.Seq2SeqTrainingArguments), which is a class that contains all the attributes to customize the training. It requires one folder name, which will be used to save the checkpoints of the model, and all other arguments are optional:
"""
# import pdb; pdb.set_trace()
batch_size = 2
model_name = model_checkpoint
# model_name = model_checkpoint.split("/")[-1]
args = Seq2SeqTrainingArguments(
f"{model_name}",
evaluation_strategy="epoch",
learning_rate=2e-5,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
weight_decay=0.01,
save_total_limit=3,
num_train_epochs=1,
predict_with_generate=True,
fp16=True,
push_to_hub=False,
generation_max_length=max_target_length,
save_strategy="epoch",
load_best_model_at_end=True,
# output_dir =
)
"""Here we set the evaluation to be done at the end of each epoch, tweak the learning rate, use the `batch_size` defined at the top of the cell and customize the weight decay. Since the `Seq2SeqTrainer` will save the model regularly and our dataset is quite large, we tell it to make three saves maximum. Lastly, we use the `predict_with_generate` option (to properly generate summaries) and activate mixed precision training (to go a bit faster).
The last argument to setup everything so we can push the model to the [Hub](https://huggingface.co/models) regularly during training. Remove it if you didn't follow the installation steps at the top of the notebook. If you want to save your model locally in a name that is different than the name of the repository it will be pushed, or if you want to push your model under an organization and not your name space, use the `hub_model_id` argument to set the repo name (it needs to be the full name, including your namespace: for instance `"sgugger/t5-finetuned-xsum"` or `"huggingface/t5-finetuned-xsum"`).
Then, we need a special kind of data collator, which will not only pad the inputs to the maximum length in the batch, but also the labels:
"""
data_collator = DataCollatorForSeq2Seq(tokenizer, model=model)
"""The last thing to define for our `Seq2SeqTrainer` is how to compute the metrics from the predictions. We need to define a function for this, which will just use the `metric` we loaded earlier, and we have to do a bit of pre-processing to decode the predictions into texts:"""
import nltk
import numpy as np
def compute_metrics(eval_pred):
predictions, labels = eval_pred
decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
# Replace -100 in the labels as we can't decode them.
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
# Rouge expects a newline after each sentence
decoded_preds = [
"\n".join(nltk.sent_tokenize(pred.strip(), language="german"))
for pred in decoded_preds
]
decoded_labels = [
"\n".join(nltk.sent_tokenize(label.strip(), language="german"))
for label in decoded_labels
]
result = metric.compute(
predictions=decoded_preds, references=decoded_labels, use_stemmer=True
)
# Extract a few results
result = {key: value.mid.fmeasure * 100 for key, value in result.items()}
# Add mean generated length
prediction_lens = [
np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions
]
result["gen_len"] = np.mean(prediction_lens)
return {k: round(v, 4) for k, v in result.items()}
"""Then we just need to pass all of this along with our datasets to the `Seq2SeqTrainer`:"""
trainer = Seq2SeqTrainer(
model,
args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"],
data_collator=data_collator,
tokenizer=tokenizer,
compute_metrics=compute_metrics,
)
import nltk
nltk.download("punkt")
"""We can now finetune our model by just calling the `train` method:"""
trainer.train()
"""You can now upload the result of the training to the Hub, just execute this instruction:"""
raw_datasets["test"]["document"][2]
input_ids = tokenizer(
raw_datasets["test"]["document"][2], return_tensors="pt"
).input_ids
outputs = model.generate(
input_ids.to(device="cuda"),
do_sample=True,
# max_length=100,
top_k=0,
temperature=1,
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
trainer.save_model()
##########################################
from transformers import AutoModelForSeq2SeqLM
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
"C:/Users/femustafa/Desktop/Language_app/t5-base"
)
model = AutoModelForSeq2SeqLM.from_pretrained(
"C:/Users/femustafa/Desktop/Language_app/t5-base"
)
def gen(sample, top_k):
input_ids = tokenizer(sample, return_tensors="pt").input_ids
outputs = model.generate(
input_ids.to(device="cpu"),
max_new_tokens=200,
do_sample=True,
# top_p=0.92,
top_k=top_k,
no_repeat_ngram_size=3,
# temperature=0.2,
# num_beams=1,
# num_return_sequences=3,
)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
import pdb
pdb.set_trace()
def temp(i, top_k):
print(raw_datasets["test"]["document"][i])
gen(raw_datasets["test"]["document"][i], top_k)
for i in range(5):
print("top 0")
temp(i, top_k=3)
print("top 5")
temp(i, top_k=30)
print("===========================")
import pdb
pdb.set_trace()