Views
No views yet
DISC-Law-SFT-Pair-QA-released.jsonl subset.r: 64lora_alpha: 16lora_dropout: 0.1per_device_train_batch_size: 4gradient_accumulation_steps: 8learning_rate: 2e-5num_train_epochs: 21from peft import PeftModel
2from transformers import AutoModelForCausalLM
3import torch
4import os
5from modelscope import AutoTokenizer
6import shutil
7
8# 保证原始模型的各个文件不遗漏保存到merge_path中
9def copy_files_not_in_B(A_path, B_path):
10 """
11 Copies files from directory A to directory B if they exist in A but not in B.
12
13 :param A_path: Path to the source directory (A).
14 :param B_path: Path to the destination directory (B).
15 """
16 # 保证路径存在
17 if not os.path.exists(A_path):
18 raise FileNotFoundError(f"The directory {A_path} does not exist.")
19 if not os.path.exists(B_path):
20 os.makedirs(B_path)
21
22 # 获取路径A中所有非权重文件
23 files_in_A = os.listdir(A_path)
24 files_in_A = set([file for file in files_in_A if not (".bin" in file or "safetensors" in file)])
25 # List all files in directory B
26 files_in_B = set(os.listdir(B_path))
27
28 # 找到所有A中存在但B中不存在的文件
29 files_to_copy = files_in_A - files_in_B
30
31 # 将文件或文件夹复制到B路径下
32 for file in files_to_copy:
33 src_path = os.path.join(A_path, file)
34 dst_path = os.path.join(B_path, file)
35
36 if os.path.isdir(src_path):
37 # 复制目录及其内容
38 shutil.copytree(src_path, dst_path)
39 else:
40 # 复制文件
41 shutil.copy2(src_path, dst_path)
42
43def merge_lora_to_base_model():
44 model_name_or_path = '...' # 原模型地址
45 adapter_name_or_path = '...' # 微调后模型的保存地址
46 save_path = '...'
47
48 # 如果文件夹不存在,就创建
49 if not os.path.exists(save_path):
50 os.makedirs(save_path)
51 tokenizer = AutoTokenizer.from_pretrained(model_name_or_path,trust_remote_code=True,)
52
53 model = AutoModelForCausalLM.from_pretrained(
54 model_name_or_path,
55 trust_remote_code=True,
56 low_cpu_mem_usage=True,
57 torch_dtype=torch.float16,
58 device_map="auto"
59 )
60 # 加载保存的 Adapter
61 model = PeftModel.from_pretrained(model, adapter_name_or_path, device_map="auto",trust_remote_code=True)
62 # 将 Adapter 合并到基础模型中
63 merged_model = model.merge_and_unload() # PEFT 的方法将 Adapter 权重合并到基础模型
64 # 保存合并后的模型
65 tokenizer.save_pretrained(save_path)
66 merged_model.save_pretrained(save_path, safe_serialization=False)
67 copy_files_not_in_B(model_name_or_path, save_path)
68 print(f"合并后的模型已保存至: {save_path}")
69
70if __name__ == '__main__':
71 merge_lora_to_base_model()