-
Notifications
You must be signed in to change notification settings - Fork 0
/
finetune_peft.py
173 lines (144 loc) · 4.93 KB
/
finetune_peft.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
import argparse
import os
import math
from dataclasses import dataclass, field
import tqdm.auto as tqdm
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import datasets
import transformers
from transformers import (
HfArgumentParser,
Trainer,
TrainingArguments,
)
from peft import (
get_peft_model,
LoraConfig,
PrefixTuningConfig,
PromptEncoderConfig,
PromptTuningConfig,
TaskType,
)
@dataclass
class FinetuneArguments:
dataset_path: str = field()
model_path: str = field()
@dataclass
class PEFTArguments:
peft_mode: str = field(default="lora")
lora_rank: int = field(default=8)
num_virtual_tokens: int = field(default=32) # Used for prompt tuning, prefix tuning and p-tuning
mapping_hidden_dim: int = field(default=1024)
def get_peft_config(peft_args: PEFTArguments, dtype):
if peft_args.peft_mode == "lora":
peft_config = LoraConfig(
task_type=TaskType.CAUSAL_LM, inference_mode=False,
r=peft_args.lora_rank,
lora_alpha=32, lora_dropout=0.1,
dtype=dtype,
)
elif peft_args.peft_mode == "prefix":
peft_config = PrefixTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=peft_args.num_virtual_tokens,
encoder_hidden_size=peft_args.mapping_hidden_dim,
prefix_projection=True,
dtype=dtype,
)
elif peft_args.peft_mode == "ptuning":
peft_config = PromptEncoderConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=peft_args.num_virtual_tokens,
encoder_hidden_size=peft_args.mapping_hidden_dim,
dtype=dtype,
)
elif peft_args.peft_mode == "prompt":
peft_config = PromptTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=peft_args.num_virtual_tokens,
dtype=dtype,
)
else:
raise KeyError(peft_args.peft_mode)
return peft_config
class CastOutputToFloat(nn.Sequential):
def forward(self, x): return super().forward(x).to(torch.float32)
def only_tunable_params(model):
requires_grad = {k: v.requires_grad for k, v in model.named_parameters()}
return {
k: v
for k, v in model.state_dict().items()
if k in requires_grad and requires_grad[k]
}
class ModifiedTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
model_out = model(
input_ids=inputs["input_ids"],
attention_mask=torch.ones_like(inputs["input_ids"]),
labels=inputs["input_ids"], # HF model does the slicing for us
)
if return_outputs:
return model_out.loss, model_out
else:
return model_out.loss
def _save(self, output_dir: Optional[str] = None, state_dict=None):
# If we are executing this function, we are the process zero, so we don't check for that.
output_dir = output_dir if output_dir is not None else self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
torch.save(
only_tunable_params(self.model),
os.path.join(output_dir, f"checkpoint.p"),
)
# Good practice: save your training arguments together with the trained model
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
def data_collator(features: list) -> dict:
return {
"input_ids": torch.stack([
torch.LongTensor(f["input_ids"])
for f in features
])
}
def save_tunable_parameters(model, path):
saved_params = {
k: v.to("cpu")
for k, v in model.named_parameters()
if v.requires_grad
}
torch.save(saved_params, path)
def main():
finetune_args, peft_args, training_args = HfArgumentParser((
FinetuneArguments,
PEFTArguments,
TrainingArguments,
)).parse_args_into_dataclasses()
print("Setup Data")
dataset = datasets.load_from_disk(finetune_args.dataset_path)
print("Setup Model")
model = transformers.LlamaForCausalLM.from_pretrained(
finetune_args.model_path,
load_in_8bit=True,
device_map="auto",
)
model.gradient_checkpointing_enable()
model.enable_input_require_grads()
model.lm_head = CastOutputToFloat(model.lm_head)
model.config.use_cache = False # silence the warnings. Please re-enable for inference!
print("Setup PEFT")
peft_config = get_peft_config(peft_args=peft_args, dtype=torch.float16)
model = get_peft_model(model, peft_config)
model = model.cuda()
print("Train")
trainer = ModifiedTrainer(
model=model,
train_dataset=dataset,
args=training_args,
data_collator=data_collator,
)
trainer.train()
save_tunable_parameters(model, os.path.join(training_args.output_dir, "params.p"))
if __name__ == "__main__":
main()