forked from chaoyi-wu/Finetune_LLAMA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
finetune_pp_peft.py
182 lines (153 loc) · 6.99 KB
/
finetune_pp_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
174
175
176
177
178
179
180
181
182
import argparse
import os
import json
import math
import tqdm.auto as tqdm
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from typing import List, Optional, Tuple, Union
import datasets
import transformers
from finetune_pp import RepeatingLoader, DatasetDataset
from finetune_peft import get_peft_config, CastOutputToFloat, save_tunable_parameters
from peft import (
get_peft_model,
LoraConfig,
PrefixTuningConfig,
PromptEncoderConfig,
PromptTuningConfig,
TaskType,
)
import os
def write_json(x, path):
with open(path, "w") as f:
f.write(json.dumps(x))
def read_json(path):
with open(path, "r") as f:
return json.load(f)
def model_forward(model, inputs):
'''
Note that this codes are used for debugging or simple classification.
'''
h = inputs
h = h.to(model.base_model.model.model.embed_tokens.weight.device)
h = model.base_model.model.model.embed_tokens(h)
for layer in model.base_model.model.model.layers:
h = h.to(layer.input_layernorm.weight.device)
h = layer(h)[0]
h = h.to(model.base_model.model.model.norm.weight.device)
h = model.base_model.model.model.norm(h)
h = model.base_model.model.lm_head(h)
return h
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str,default = './LLAMA_Model/llama-7b')
parser.add_argument("--dataset_path", type=str,default = './Data_sample/UMLSE_Train_Tokenized')
parser.add_argument("--save_dir", type=str,default = './Fine_Tuning_Results/UMLSE_Lora')
parser.add_argument("--batch_size", type=int, default=4)
parser.add_argument("--learning_rate", type=float, default=1e-4)
parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
parser.add_argument("--num_train_steps", type=int,default = 10000)
parser.add_argument("--save_interval", type=int, default = 1000)
parser.add_argument("--peft_mode", type=str, default="lora")
parser.add_argument("--lora_rank", type=int, default=8)
parser.add_argument("--num_virtual_tokens", type=int, default=32)
parser.add_argument("--mapping_hidden_dim", type=int, default=1024)
args = parser.parse_args()
os.makedirs(args.save_dir, exist_ok=True)
latest_path = os.path.join(args.save_dir, "latest.json")
print("Setup Data")
dataset = datasets.load_from_disk(args.dataset_path)
dataloader = RepeatingLoader(torch.utils.data.DataLoader(
DatasetDataset(dataset),
batch_size=args.batch_size,
shuffle=True
))
print("Setup Model")
# The auto/balance balancing strategy doesn't seem to work correctly,
# so we manually compute the mappings.
num_layers = read_json(os.path.join(args.model_path, "config.json"))["num_hidden_layers"]
device_ids = list(range(torch.cuda.device_count()))
device_map = {
"model.embed_tokens": device_ids[0],
"model.norm.weight": device_ids[-1],
"lm_head": device_ids[-1],
}
allocations = [
device_ids[i] for i in
sorted(list(range(len(device_ids))) * math.ceil(num_layers / len(device_ids)))
]
for layer_i, device_id in enumerate(allocations):
device_map[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.mlp.down_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.mlp.up_proj.weight"] = device_id
device_map[f"model.layers.{layer_i}.input_layernorm.weight"] = device_id
device_map[f"model.layers.{layer_i}.post_attention_layernorm.weight"] = device_id
device_map[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = device_id
model = transformers.LlamaForCausalLM.from_pretrained(
args.model_path,
#load_in_8bit=True,
device_map=device_map,
)
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=args)
model = get_peft_model(model, peft_config)
for layer_i in range(len(model.base_model.model.model.layers)):
device = model.base_model.model.model.layers[layer_i].self_attn.q_proj.weight.device
model.base_model.model.model.layers[layer_i].self_attn.q_proj.lora_B.to(device)
model.base_model.model.model.layers[layer_i].self_attn.q_proj.lora_A.to(device)
model.base_model.model.model.layers[layer_i].self_attn.v_proj.lora_B.to(device)
model.base_model.model.model.layers[layer_i].self_attn.v_proj.lora_A.to(device)
print("Setup optimizer")
opt = torch.optim.AdamW([
p
for p in model.parameters()
if p.requires_grad
], lr=args.learning_rate)
# Restart progress
if os.path.exists(latest_path):
start = read_json(latest_path)["latest_step"]
model.load_state_dict(
torch.load(os.path.join(os.path.join(args.save_dir, f"params-{start + 1:06d}.p"))), strict=False)
opt.load_state_dict(
torch.load(os.path.join(os.path.join(args.save_dir, f"opt-{start + 1:06d}.p"))),map_location='cpu')
else:
start = 0
# Train (maybe can replace with Trainer? I think Trainer might mess up the device mappings though.)
print("Start training")
generator = iter(dataloader)
for step in tqdm.trange(args.num_train_steps, initial=start):
input_ids, labels = next(generator)
# logits = model_forward(model, input_ids)
# loss = F.cross_entropy(
# logits.view(-1, model.config.vocab_size),
# labels.view(-1).to(logits.device),
# )
output = model(input_ids = input_ids, labels = labels)
loss = output['loss']
loss.backward()
opt.step()
actual_step = step + 1
if step % 10 == 0:
print(f"Loss={loss.item():.3f}")
if actual_step % args.gradient_accumulation_steps == 0:
opt.zero_grad()
if actual_step % args.save_interval == 0:
save_tunable_parameters(model, os.path.join(args.save_dir, f"params-{actual_step:06d}.p"))
#save_tunable_parameters(opt.state_dict(), os.path.join(args.save_dir, f"opt-{actual_step:06d}.p"))
torch.save(opt.state_dict(), os.path.join(args.save_dir, f"opt-{actual_step:06d}.p"))
write_json({"latest_step": step}, latest_path)
save_tunable_parameters(model, os.path.join(args.save_dir, "params-last.p"))
if __name__ == "__main__":
#os.environ['CUDA_VISIBLE_DEVICES'] = '1,2,3,5'
main()
# CUDA_VISIBLE_DEVICES='0,1,2,3' python finetune_pp_peft.py