-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peft-fine-tuning.py
339 lines (271 loc) · 11.1 KB
/
peft-fine-tuning.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
from peft import LoraConfig, get_peft_model, TaskType
from datasets import load_dataset
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from transformers import GenerationConfig, TrainingArguments, Trainer
import torch
import time
import evaluate
import pandas as pd
import numpy as np
import datetime
# Check if MPS is available and set the device
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
print(f"Using device: {device}")
# Common things
dash_line = '-'.join('' for x in range(100))
equal_line = '='.join('' for x in range(100))
def print_number_of_trainable_model_parameters(model):
trainable_model_params = 0
all_model_params = 0
for _, param in model.named_parameters():
all_model_params += param.numel()
if param.requires_grad:
trainable_model_params += param.numel()
return f"""=>
{trainable_model_params}
({100 * trainable_model_params / all_model_params:.2f}%)
of {all_model_params}
"""
def tokenize_function(example):
start_prompt = 'Summarize the following conversation.\n\n'
end_prompt = '\n\nSummary: '
prompt = [start_prompt + dialogue +
end_prompt for dialogue in example["dialogue"]]
example['input_ids'] = tokenizer(
prompt, padding="max_length",
truncation=True, return_tensors="pt").input_ids.to(device)
example['labels'] = tokenizer(
example["summary"], padding="max_length",
truncation=True, return_tensors="pt").input_ids.to(device)
return example
# Load the dataset
huggingface_dataset_name = "knkarthick/dialogsum"
print(f"\nLoading dataset {huggingface_dataset_name}...")
print(equal_line)
dataset = load_dataset(huggingface_dataset_name)
# Load the model and tokenizer
print("\nLoading model and tokenizer...")
print(equal_line)
model_name = 'google/flan-t5-base'
original_model = AutoModelForSeq2SeqLM.from_pretrained(
# If not using mac, use bfloat16
model_name, torch_dtype=torch.float32).to(device)
tokenizer = AutoTokenizer.from_pretrained(
model_name, clean_up_tokenization_spaces=True)
print("Number of trainable model parameters in original model:")
print(print_number_of_trainable_model_parameters(original_model))
# Before fine-tuning, let's look at zero-shot performance
index = 200 # Example we chose to look at
print(f"\nZero-shot performance before fine-tuning for {index}th row:")
print(equal_line)
dialogue = dataset['test'][index]['dialogue']
summary = dataset['test'][index]['summary']
prompt = f"""
Summarize the following conversation.
{dialogue}
Summary:
"""
inputs = tokenizer(prompt, return_tensors='pt').to(device)
output = tokenizer.decode(
original_model.generate(
inputs["input_ids"],
max_new_tokens=200,
)[0],
skip_special_tokens=True
)
print(f'INPUT PROMPT:\n{prompt}')
print(dash_line)
print(f'BASELINE HUMAN SUMMARY:\n{summary}\n')
print(dash_line)
print(f'MODEL GENERATION - ZERO SHOT:\n{output}')
print("\nDataset tokenization and batching...")
print(equal_line)
# The dataset actually contains 3 diff splits: train, validation, test.
# The tokenize_function code is handling all data across all splits in batches.
tokenized_datasets = dataset.map(tokenize_function, batched=True)
tokenized_datasets = tokenized_datasets.remove_columns(
['id', 'topic', 'dialogue', 'summary',])
tokenized_datasets = tokenized_datasets.filter(
lambda example, index: index % 100 == 0, with_indices=True)
print("Shapes of the datasets:")
print(f"Training: {tokenized_datasets['train'].shape}")
print(f"Validation: {tokenized_datasets['validation'].shape}")
print(f"Test: {tokenized_datasets['test'].shape}")
# print(tokenized_datasets)
# Fine-tuning the model if you have a cached version
print("\nFine-tuning the model with PEFT...")
print(equal_line)
now = datetime.datetime.now()
print("Fine-tuning start tine : ")
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# from peft import PeftModel, PeftConfig
# peft_model_base = AutoModelForSeq2SeqLM.from_pretrained(
# "google/flan-t5-base", torch_dtype=torch.bfloat16)
# tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
# peft_model = PeftModel.from_pretrained(peft_model_base,
# './peft-dialogue-summary-checkpoint-from-s3/',
# torch_dtype=torch.bfloat16,
# is_trainable=False)
# print("Number of trainable model parameters in trained PEFT model:")
# Define the model PEFT config
lora_config = LoraConfig(
r=32, # Rank
lora_alpha=32,
target_modules=["q", "v"],
lora_dropout=0.05,
bias="none",
task_type=TaskType.SEQ_2_SEQ_LM # FLAN-T5
)
peft_model = get_peft_model(original_model, lora_config)
print(print_number_of_trainable_model_parameters(peft_model))
# Define the training arguments
output_dir = f'./peft-dialogue-summary-training-{str(int(time.time()))}'
peft_training_args = TrainingArguments(
output_dir=output_dir,
auto_find_batch_size=True,
learning_rate=1e-3, # Higher learning rate than full fine-tuning.
num_train_epochs=1,
logging_steps=1,
max_steps=1
)
peft_trainer = Trainer(
model=peft_model,
args=peft_training_args,
train_dataset=tokenized_datasets["train"],
)
# PEFT is relatively faster. Based on the model size, you choose to train
# and save it offline
# Otherwise, it will take days or may not even complete on a small laptop.
peft_trainer.train()
peft_model_path = "./peft-dialogue-summary-checkpoint-local"
# Cache it if you want to use it later.
peft_trainer.model.save_pretrained(peft_model_path)
tokenizer.save_pretrained(peft_model_path)
print("Fine-tuning end tine : ")
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print(print_number_of_trainable_model_parameters(peft_model))
# Evaluate the model qualitatively
print("\nEvaluating the model qualitatively...")
print(equal_line)
dialogue = dataset['test'][index]['dialogue']
baseline_human_summary = dataset['test'][index]['summary']
prompt = f"""
Summarize the following conversation.
{dialogue}
Summary: """
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
original_model_outputs = original_model.generate(
input_ids=input_ids, generation_config=GenerationConfig(max_new_tokens=200,
num_beams=1))
original_model_text_output = tokenizer.decode(
original_model_outputs[0], skip_special_tokens=True)
peft_model_outputs = peft_model.generate(
input_ids=input_ids, generation_config=GenerationConfig(max_new_tokens=200,
num_beams=1))
peft_model_text_output = tokenizer.decode(
peft_model_outputs[0], skip_special_tokens=True)
print(f'PEFT MODEL: {peft_model_text_output}')
# Evaluate the model quantitatively
total = 10
print("\nEvaluating the model quantitatively using ROUGE...")
print(equal_line)
dialogues = dataset['test'][0:total]['dialogue']
human_baseline_summaries = dataset['test'][0:total]['summary']
original_model_summaries = []
peft_model_summaries = []
for idx, dialogue in enumerate(dialogues):
prompt = f"""
Summarize the following conversation.
{dialogue}
Summary: """
print(f"Generating summary for row {idx}...")
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
human_baseline_text_output = human_baseline_summaries[idx]
original_model_outputs = original_model.generate(
input_ids=input_ids, generation_config=GenerationConfig(
max_new_tokens=200))
original_model_text_output = tokenizer.decode(
original_model_outputs[0], skip_special_tokens=True)
peft_model_outputs = peft_model.generate(
input_ids=input_ids, generation_config=GenerationConfig(
max_new_tokens=200))
peft_model_text_output = tokenizer.decode(
peft_model_outputs[0], skip_special_tokens=True)
original_model_summaries.append(original_model_text_output)
peft_model_summaries.append(peft_model_text_output)
zipped_summaries = list(
zip(human_baseline_summaries, original_model_summaries,
peft_model_summaries))
print("\nComparing human vs original vs peft model summaries...\n")
df = pd.DataFrame(zipped_summaries, columns=[
'human_baseline_summaries',
'original_model_summaries',
'peft_model_summaries'])
print(df)
print("\nEvaluating the model quantitatively using ROUGE...")
print(equal_line)
rouge = evaluate.load('rouge')
human_baseline_summaries = dataset['test'][0:total]['summary']
original_model_results = rouge.compute(
predictions=original_model_summaries,
references=human_baseline_summaries[0:len(original_model_summaries)],
use_aggregator=True,
use_stemmer=True,
)
peft_model_results = rouge.compute(
predictions=peft_model_summaries,
references=human_baseline_summaries[0:len(peft_model_summaries)],
use_aggregator=True,
use_stemmer=True,
)
print('ORIGINAL MODEL:')
print(original_model_results)
print('PEFT MODEL:')
print(peft_model_results)
# check performance on the full test set
print("\nEval the model quantitatively using ROUGE on the full test set.")
print(equal_line)
results = pd.read_csv("data/ds-training-results.csv")
human_baseline_summaries = results['human_baseline_summaries'].values
original_model_summaries = results['original_model_summaries'].values
peft_model_summaries = results['peft_model_summaries'].values
human_baseline_summaries = results['human_baseline_summaries'].values
original_model_summaries = results['original_model_summaries'].values
instruct_model_summaries = results['instruct_model_summaries'].values
peft_model_summaries = results['peft_model_summaries'].values
original_model_results = rouge.compute(
predictions=original_model_summaries,
references=human_baseline_summaries[0:len(original_model_summaries)],
use_aggregator=True,
use_stemmer=True,
)
instruct_model_results = rouge.compute(
predictions=instruct_model_summaries,
references=human_baseline_summaries[0:len(instruct_model_summaries)],
use_aggregator=True,
use_stemmer=True,
)
peft_model_results = rouge.compute(
predictions=peft_model_summaries,
references=human_baseline_summaries[0:len(peft_model_summaries)],
use_aggregator=True,
use_stemmer=True,
)
print('ORIGINAL MODEL:')
print(original_model_results)
print('INSTRUCT MODEL:')
print(instruct_model_results)
print('PEFT MODEL:')
print(peft_model_results)
print("\nAbsolute percentage improvement of PEFT MODEL over ORIGINAL MODEL")
print(equal_line)
improvement = (np.array(list(peft_model_results.values())) -
np.array(list(original_model_results.values())))
for key, value in zip(peft_model_results.keys(), improvement):
print(f'{key}: {value*100:.2f}%')
print("\nAbsolute percentage improvement of PEFT MODEL over INSTRUCT MODEL")
print(equal_line)
improvement = (np.array(list(peft_model_results.values())) -
np.array(list(instruct_model_results.values())))
for key, value in zip(peft_model_results.keys(), improvement):
print(f'{key}: {value*100:.2f}%')