-
Notifications
You must be signed in to change notification settings - Fork 35
/
finetune_peft.py
158 lines (133 loc) · 4.36 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
import argparse
import os
import math
from dataclasses import dataclass, field
import tqdm.auto as tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import os
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):
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
)
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,
)
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,
)
elif peft_args.peft_mode == "prompt":
peft_config = PromptTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=peft_args.num_virtual_tokens,
)
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)
class ModifiedTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
return 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
).loss
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)
model = get_peft_model(model, peft_config)
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__":
#os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,5'
main()
'''
CUDA_VISIBLE_DEVICES='0,1,2,5' python finetune_peft.py \
--model_path /nvme/zhangruipeng/wuchaoyi/wuchaoyi/llama/llama-7b \
--dataset_path /nvme/zhangruipeng/wuchaoyi/minimal-llama/UMLSE_train \
--peft_mode lora \
--lora_rank 8 \
--per_device_train_batch_size 1 \
--gradient_accumulation_steps 1 \
--max_steps 2500 \
--learning_rate 2e-4 \
--fp16 \
--logging_steps 10 \
--output_dir /nvme/zhangruipeng/wuchaoyi/minimal-llama/fine_tuning_results
'''