数据集
数据的收集:Python爬虫js逆向+APP逆向
数据格式的转化:pdf转markdown使用的是API(可以省略)
数据集问题和答案的生成:ChatGPT
非法字符的清洗:python代码
def clean_text(text):
# 使用正则表达式移除特定字符
cleaned_text = re.sub(r'[\[\]{}\\]', '', text)
return cleaned_text
input和output的存储:python+excel
def process_markdown_file(file_path):
"""
读取并处理Markdown文件。
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
cleaned_content = clean_text(content)
return cleaned_content
except FileNotFoundError:
print(f"文件未找到: {file_path}")
return None
def save_to_excel(data, output_path):
"""
将处理后的内容及文件名保存到Excel文件中。
"""
wb = Workbook()
ws = wb.active
ws.append(['文件名', '文章内容']) # 添加标题行
for file_name, content in data:
ws.append([file_name, content])
wb.save(output_path)
def process_folder(folder_path, output_path):
"""
处理文件夹中的所有Markdown文件。
"""
processed_data = []
for file in os.listdir(folder_path):
if file.endswith('.md'):
file_path = os.path.join(folder_path, file)
processed_content = process_markdown_file(file_path)
if processed_content:
processed_data.append((file, processed_content))
if processed_data:
save_to_excel(processed_data, output_path)
print("所有文件内容已保存到Excel文件")
else:
print("没有处理任何文件")
json格式:python代码
# 将数据转换为特定格式的JSON
json_data = []
for index, row in df.iterrows():
# 清洗文章和问题中的特定字符
cleaned_article = clean_text(row['文章'])
cleaned_question = clean_text(row['问题'])
item = {
"id": f"existence_{index + 1}",
"input": f"基于下面财报内容,要求回答内容完全基于截取片段,如果基于截取片段无法回答,则回复“基于上文内容,无法回答该问题”\n{cleaned_article}\n问题:{cleaned_question}\n",
"output": str(row['回答']) # 确保输出是字符串格式
}
json_data.append(item)
数据集样例:
[{
"id": "existence_38",
"input": "基于下面财报内容,要求回答内容完全基于截取片段,如果基于截取片段无法回答,则回复“基于上文内容,无法回答该问题”\n广州白云国际机场股份有限公司2003年年度报告重要提示公司董事会及董事保证本报告所载资料不存在虚假记载、误导性陈述或者重大遗漏,并对其内容的真实性、准确性和完整性承担个别及连带责任。公司负责人董事长刘子静先生、主管会计工作负责人总经理崔建国先生、会计机构负责人财务部经理莫名贞女士声明:保证年度报告中财务报告的真实、完整。\n问题:2003年度,公司的主要利润指标中的营业利润是多少?\n",
"output": "无法回答该问题"
},
{
"id": "existence_39",
"input": "基于下面财报内容,要求回答内容完全基于截取片段,如果基于截取片段无法回答,则回复“基于上文内容,无法回答该问题”\n公司的主要业务收入在2003年较上年增长了13%\n问题:公司的主要业务收入在2003年较上年增长了多少百分比?\n",
"output": "13"
}]
部署
环境:
python == 3.10
pip install transformers==4.33.3
创建虚拟环境:conda create -n baichuan python=3.10
进入虚拟环境:conda activate baichuan
克隆模型:git clone https://github.com/baichuan-inc/Baichuan2.git
安装依赖:pip install -r requirements.txt
更新依赖:pip install --upgrade sentencepiece
补充依赖:pip install xformers
运行测试:python cli_demo.py
部署问题:
1:huggingface无法访问问题
网址:https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/tree/main
名称:baichuan-inc/Baichuan2-13B-Chat
镜像网站:https://hf-mirror.com
# 下载大型文件
wget https://hf-mirror.com/baichuan-inc/Baichuan2-13B-Chat/resolve/main/pytorch_model-00001-of-00003.bin?download=true -O pytorch_model-00001-of-00003.bin
wget https://hf-mirror.com/baichuan-inc/Baichuan2-13B-Chat/resolve/main/pytorch_model-00002-of-00003.bin?download=true -O pytorch_model-00002-of-00003.bin
wget https://hf-mirror.com/baichuan-inc/Baichuan2-13B-Chat/resolve/main/pytorch_model-00003-of-00003.bin?download=true -O pytorch_model-00003-of-00003.bin
2:代码修改模型位置 # 设置模型路径
model_path = "/root/baichuan2_13B/Baichuan2-13B-Chat"
model = AutoModelForCausalLM.from_pretrained(
model_path,
torch_dtype=torch.float16,
device_map="auto",
trust_remote_code=True
)
model.generation_config = GenerationConfig.from_pretrained(
model_path
)
tokenizer = AutoTokenizer.from_pretrained(
model_path,
use_fast=False,
trust_remote_code=True
)
return model, tokenizer
微调
基于LLAMA:https://github.com/hiyouga/LLaMA-Factory.git
进入虚拟环境:conda activate baichuan
加入数据集:LLaMA-Factory/data/test.json
修改数据集设置:LLaMA-Factory/data/dataset_info.json
"test": {
"file_name": "test.json",
"columns": {
"prompt": "input",
"response": "output"
}
}
用LoRA启用多GPU微调:LLaMA-Factory/fine-tune.sh
CUDA_VISIBLE_DEVICES=1,2,3,4 torchrun --nproc_per_node 4 /root/baichuan2_13B/LLaMA-Factory/src/train_bash.py \
--stage sft \
--model_name_or_path /root/baichuan2_13B/Baichuan2-13B-Chat \
--do_train True \
--finetuning_type lora \
--template baichuan \
--flash_attn False \
--shift_attn False \
--dataset_dir data \
--dataset test \
--cutoff_len 1024 \
--learning_rate 3e-05 \
--num_train_epochs 70.0 \
--max_samples 100000 \
--per_device_train_batch_size 4 \
--gradient_accumulation_steps 2 \
--lr_scheduler_type cosine \
--max_grad_norm 0.5 \
--logging_steps 5 \
--save_steps 20 \
--warmup_steps 0 \
--neft_alpha 0 \
--train_on_prompt False \
--upcast_layernorm False \
--lora_rank 8 \
--lora_dropout 0.1 \
--lora_target W_pack \
--resume_lora_training False \
--output_dir saves/Baichuan-13B-Chat/lora/train_test\
--fp16 True \
--plot_loss True
微调问题
1:百川 loss为0
LLaMA-Factory/src/llmtuner/train/pt/workflow.py
使用load_in_8bit:
model, tokenizer = load_model_and_tokenizer(model_args,finetuning_args,training_args.do_train,load_in_8bit=True)
LLaMA-Factory/fine-tune.sh
使用:
--fp16 True \