-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
205 lines (175 loc) · 6.61 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
import os
import json
import torch
from argparse import ArgumentParser
from loguru import logger
from transformers import (
set_seed,
HfArgumentParser,
TrainingArguments,
LlamaTokenizer,
DataCollatorForLanguageModeling,
DataCollatorForSeq2Seq,
Trainer,
)
from model.configuration_llama import LlamaConfig
from model.modeling_llama import LlamaForCausalLM
import torch.nn as nn
from preprocess import get_dataset, IGNORE_INDEX
from argument import CustomizedArguments
from peft import LoraConfig, get_peft_model, TaskType
def setup_everything():
parser = ArgumentParser()
parser.add_argument(
"--train_args_file", type=str, default="hparams/debug.json"
)
parser.add_argument("--local_rank", type=int, help="")
args = parser.parse_args()
train_args_file = args.train_args_file
# 读取训练的参数配置
parser = HfArgumentParser((CustomizedArguments, TrainingArguments))
# 解析得到自定义参数和Trainer自带参数
args, training_args = parser.parse_json_file(json_file=train_args_file)
# 创建输出目录
if not os.path.exists(training_args.output_dir):
os.makedirs(training_args.output_dir)
logger.add(os.path.join(training_args.output_dir, "train.log"))
logger.info("Training arguments have been saved to:{}".format(os.path.join(training_args.output_dir, "train.log")))
# 加载训练配置文件
with open(train_args_file, "r") as f:
train_args = json.load(f)
# 保存训练参数到输出目录
with open(os.path.join(training_args.output_dir, "train_args.json"), "w") as f:
json.dump(train_args, f, indent=4)
# 设置随机种子
set_seed(training_args.seed)
# check some setting
assert args.task_type in [
"pretrain",
"sft",
], "task_type should be in ['pretrain', 'sft']"
assert args.train_mode in [
"full",
"lora",
"dora",
], "train_mode should be in ['full', 'lora', 'dora']"
assert (
sum([training_args.fp16, training_args.bf16]) == 1
), "only one of fp16 and bf16 can be True"
return args, training_args
def find_all_linear_names(model, train_mode):
"""
找出所有全连接层, 为所有全连接添加adapter
"""
assert train_mode in ["lora", "dora"]
cls = nn.Linear
lora_module_names = set()
for name, module in model.named_modules():
if isinstance(module, cls):
names = name.split(".")
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
if "lm_head" in lora_module_names: # needed for 16-bit
lora_module_names.remove("lm_head")
lora_module_names = list(lora_module_names)
logger.info(f"LoRA target module names: {lora_module_names}")
return lora_module_names
def load_model(args, training_args):
"""
加载模型
"""
assert training_args.bf16 or training_args.fp16, "bf16 or fp16 should be True"
logger.info(f"Loading model from base model: {args.model_name_or_path}")
logger.info(f"Train model with {args.train_mode}")
torch_dtype = torch.float16 if training_args.fp16 else torch.bfloat16
kwargs = dict(torch_dtype=torch_dtype)
if args.flash_attn:
kwargs.update(attn_implementation="flash_attention_2")
config = LlamaConfig.from_pretrained("./model")
config.update(kwargs)
logger.info(f"model config {config}")
model = LlamaForCausalLM(config=config)
if args.train_mode == "lora" and args.task_type in ["pretrain", "sft"]:
# For backward compatibility
if hasattr(model, "enable_input_require_grads"):
model.enable_input_require_grads()
else:
def make_inputs_require_grad(module, input, output):
output.requires_grad_(True)
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
# init peft_config
if args.train_mode == "full":
peft_config = None
else:
# 目前默认lora target是所有全连接层
target_modules = find_all_linear_names(model, args.train_mode)
peft_config = LoraConfig(
r=args.lora_rank,
lora_alpha=args.lora_alpha,
lora_dropout=args.lora_dropout,
target_modules=target_modules,
task_type=TaskType.CAUSAL_LM,
use_dora=args.use_dora,
)
# init peft model
if args.train_mode in ["lora", "dora"] and args.task_type in ["pretrain", "sft"]:
model = get_peft_model(model, peft_config)
logger.info(
f"memory footprint of model: {model.get_memory_footprint() / (1024 * 1024 * 1024)} GB"
)
model.print_trainable_parameters()
# 计算模型参数量
total = sum(p.numel() for p in model.parameters())
logger.info("Total model params: %.2fM" % (total / 1e6))
return {"model": model, "peft_config": peft_config}
def init_components(args, training_args):
"""
初始化各个组件
"""
training_args.ddp_find_unused_parameters = False
logger.info("Initializing components...")
# 加载tokenzier
tokenizer = LlamaTokenizer.from_pretrained(
args.model_name_or_path,
padding_side="right",
use_fast=False,
)
logger.info(f"vocab_size of tokenizer: {tokenizer.vocab_size}")
# 加载模型
components = load_model(args, training_args)
model = components['model']
# 初始化dataset和collator
if args.task_type == "pretrain":
logger.info("Train model with pretrain task")
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
elif args.task_type == "sft":
logger.info("Train model with sft task")
data_collator = DataCollatorForSeq2Seq(
tokenizer=tokenizer, label_pad_token_id=IGNORE_INDEX
)
train_dataset = get_dataset(tokenizer, args, training_args)
# 初始化Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
tokenizer=tokenizer,
data_collator=data_collator,
)
return trainer
def main():
args, training_args = setup_everything()
# 加载各种组件
trainer = init_components(args, training_args)
# 开始训练
logger.info("*** starting training ***")
train_result = trainer.train()
# 保存最好的checkpoint
final_save_path = os.path.join(training_args.output_dir)
trainer.save_model(final_save_path) # Saves the tokenizer too
# 保存训练指标
metrics = train_result.metrics
trainer.log_metrics("train", metrics)
trainer.save_metrics("train", metrics)
trainer.save_state()
if __name__ == "__main__":
main()