本文以Qwen2作为基座大模型,通过指令微调的方式做高精度的命名实体识别(NER)
数据集:
https://huggingface.co/datasets/qgyd2021/chinese_ner_sft/tree/main/data
ccfbdci.jsonl:该数据集主要被用于训练命名实体识别模型。
原始模型:modelscope下载Qwen2-1.5B-Instruct模型
train.py:
import json
import pandas as pd
import torch
from datasets import Dataset
from modelscope import snapshot_download, AutoTokenizer
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForCausalLM, TrainingArguments, Trainer, DataCollatorForSeq2Seq
import os
def dataset_jsonl_transfer(origin_path, new_path):
"""
将原始数据集转换为大模型微调所需数据格式的新数据集
"""
messages = []
# 读取旧的JSONL文件
with open(origin_path, "r") as file:
for line in file:
# 解析每一行的json数据
data = json.loads(line)
input_text = data["text"]
entities = data["entities"]
match_names = ["地点", "人名", "地理实体", "组织"]
entity_sentence = ""
for entity in entities:
entity_json = dict(entity)
entity_text = entity_json["entity_text"]
entity_names = entity_json["entity_names"]
for name in entity_names:
if name in match_names:
entity_label = name
break
entity_sentence += f"""{{"entity_text": "{entity_text}", "entity_label": "{entity_label}"}}"""
if entity_sentence == "":
entity_sentence = "没有找到任何实体"
message = {
"instruction": """你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如 {"entity_text": "南京", "entity_label": "地理实体"} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出"没有找到任何实体". """,
"input": f"文本:{input_text}",
"output": entity_sentence,
}
messages.append(message)
# 保存重构后的JSONL文件
with open(new_path, "w", encoding="utf-8") as file:
for message in messages:
file.write(json.dumps(message, ensure_ascii=False) + "\n")
def process_func(example):
"""
将数据集进行预处理, 处理成模型可以接受的格式
"""
MAX_LENGTH = 384
input_ids, attention_mask, labels = [], [], []
system_prompt = """你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如 {"entity_text": "南京", "entity_label": "地理实体"} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出"没有找到任何实体"."""
instruction = tokenizer(
f"<|im_start|>system\n{system_prompt}<|im_end|>\n<|im_start|>user\n{example['input']}<|im_end|>\n<|im_start|>assistant\n",
add_special_tokens=False,
)
response = tokenizer(f"{example['output']}", add_special_tokens=False)
input_ids = instruction["input_ids"] + response["input_ids"] + [tokenizer.pad_token_id]
attention_mask = (
instruction["attention_mask"] + response["attention_mask"] + [1]
)
labels = [-100] * len(instruction["input_ids"]) + response["input_ids"] + [tokenizer.pad_token_id]
if len(input_ids) > MAX_LENGTH: # 做一个截断
input_ids = input_ids[:MAX_LENGTH]
attention_mask = attention_mask[:MAX_LENGTH]
labels = labels[:MAX_LENGTH]
return {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
def predict(messages, model, tokenizer):
device = "cuda"
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
generated_ids = model.generate(
model_inputs.input_ids,
max_new_tokens=512,
use_cache=False # 关闭use_cache
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print(response)
return response
model_id = "qwen/Qwen2-1.5B-Instruct"
# 在modelscope上下载Qwen模型到本地目录下
path = "/root/autodl-tmp/sft"
model_dir = snapshot_download(model_id, cache_dir=path, revision="master")
print("model_dir:", model_dir)
# Transformers加载模型权重
tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", torch_dtype=torch.bfloat16)
model.enable_input_require_grads() # 开启梯度检查点
# 加载、处理数据集
train_dataset_path = "/root/autodl-tmp/sft/ccfbdci.jsonl" # 命名实体识别任务-数据集
train_jsonl_new_path = "/root/autodl-tmp/sft/ccf_train.jsonl" # 数据集格式转换后
if not os.path.exists(train_jsonl_new_path):
dataset_jsonl_transfer(train_dataset_path, train_jsonl_new_path)
# 原始数据:
# {
# "text": "马云在杭州创立了阿里巴巴",
# "entities": [
# {"entity_text": "马云", "entity_names": ["人名"]},
# {"entity_text": "杭州", "entity_names": ["地点", "地理实体"]},
# {"entity_text": "阿里巴巴", "entity_names": ["组织"]}
# ]
# }
# 转换后数据:
# {
# "instruction": "你是一个文本实体识别领域的专家...",
# "input": "文本:马云在杭州创立了阿里巴巴",
# "output": "{\"entity_text\": \"马云\", \"entity_label\": \"人名\"}{\"entity_text\": \"杭州\", \"entity_label\": \"地理实体\"}{\"entity_text\": \"阿里巴巴\", \"entity_label\": \"组织\"}"
# }
# 得到训练集
print("train_jsonl_new_path:", train_jsonl_new_path)
total_df = pd.read_json(train_jsonl_new_path, lines=True) # 读取新的训练数据文件,转换为 pandas DataFrame
train_df = total_df[int(len(total_df) * 0.1):] # 划分训练集:取后 90% 的数据(跳过前 10%)
train_ds = Dataset.from_pandas(train_df) # 将pandas DataFrame 转换为 Hugging Face Dataset 对象
# 对训练集应用数据处理函数(如文本清洗、格式转换等),并移除原始列
train_dataset = train_ds.map(
process_func, # 数据处理函数
remove_columns=train_ds.column_names # 删除原始列
)
config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
inference_mode=False, # 训练模式
r=8, # Lora 秩
lora_alpha=32, # Lora alaph,具体作用参见 Lora 原理
lora_dropout=0.1, # Dropout 比例
)
model = get_peft_model(model, config)
args = TrainingArguments(
output_dir="/root/autodl-tmp/sft/output/Qwen2-NER",
per_device_train_batch_size=4,
per_device_eval_batch_size=4,
gradient_accumulation_steps=4,
logging_steps=10,
num_train_epochs=2,
save_steps=100,
learning_rate=1e-4,
save_on_each_node=True,
gradient_checkpointing=True, # 开启梯度检查点
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_dataset,
data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),
)
print("开始train")
trainer.train()
# 随机20条用作测试集,测试模型
test_df = total_df[:int(len(total_df) * 0.1)].sample(n=20)
print("test_df:", test_df)
print("开始测试")
test_text_list = []
for index, row in test_df.iterrows():
instruction = row['instruction']
input_value = row['input']
messages = [
{"role": "system", "content": f"{instruction}"},
{"role": "user", "content": f"{input_value}"}
]
response = predict(messages, model, tokenizer) # 调用模型预测生成response
messages.append({"role": "assistant", "content": f"{response}"}) # 追加助手回复到对话
result_text = f"{messages[0]}\n\n{messages[1]}\n\n{messages[2]}" # 格式化结果文本
test_text_list.append(result_text)
print(test_text_list)
推理训练好的模型
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
def predict(messages, model, tokenizer):
device = "cuda"
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
model_inputs = tokenizer([text], return_tensors="pt").to(device)
generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
return response
# 加载原下载路径的tokenizer和model
model_dir = "/root/autodl-tmp/sft/qwen/Qwen2-1___5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_dir, device_map="auto", torch_dtype=torch.bfloat16)
# 加载训练好的Lora模型,将下面的[checkpoint-XXX]替换为实际的checkpoint文件名名称
output_dir = "/root/autodl-tmp/sft/output/Qwen2-NER/checkpoint-1700" # todo
model = PeftModel.from_pretrained(model, model_id=output_dir)
input_text = "西安电子科技大学的陈志明爱上了隔壁西北工业大学苏春红,他们约定好毕业后去中国的苏州定居。"
test_texts = {
"instruction": """你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如; {"entity_text": "南京", "entity_label": "地理实体"} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出"没有找到任何实体". """,
"input": f"文本:{input_text}"
}
instruction = test_texts['instruction']
input_value = test_texts['input']
messages = [
{"role": "system", "content": f"{instruction}"},
{"role": "user", "content": f"{input_value}"}
]
response = predict(messages, model, tokenizer)
print(response)
输出结果如下:
(t5_4090) root@autodl-container-f172458fba-0ea9d9a1:~/autodl-tmp/sft# nohup python -u sft_test.py > train.log 2>&1 &
[1] 5437
(t5_4090) root@autodl-container-f172458fba-0ea9d9a1:~/autodl-tmp/sft# tail -f train.log
nohup: ignoring input
The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results.
{"entity_text": "西安电子科技大学", "entity_label": "组织"}{"entity_text": "陈志明", "entity_label": "人名"}{"entity_text": "西北工业大学", "entity_label": "组织"}{"entity_text": "苏春红", "entity_label": "人名"}{"entity_text": "中国", "entity_label": "地理实体"}{"entity_text": "苏州", "entity_label": "地理实体"}