当前位置:   article > 正文

Qwen2大模型微调入门实战-命名实体识别(NER)任务

qwen2-1.5b-instruct

作者:林泽毅,Ph.D.@XDU;SwanLab联合创始人
声明:本文只做分享,版权归原作者,侵权私信删除!
原文:https://zhuanlan.zhihu.com/p/704463319

编辑:青稞AI

Qwen2[1]是通义千问团队最近开源的大语言模型,由阿里云通义实验室研发。

以Qwen2作为基座大模型,通过指令微调的方式做高精度的命名实体识别(NER),是学习入门LLM微调、建立大模型认知的非常好的任务。

6a09749c95f8916871ff870b451ac174.jpeg

使用LoRA方法训练,1.5B模型对显存要求不高,10GB左右就可以跑。

在本文中,我们会使用 Qwen2-1.5b-Instruct 模型在 中文NER[2] 数据集上做指令微调训练,同时使用SwanLab[3]监控训练过程、评估模型效果。

  • • 代码:完整代码直接看本文第5节 或 Github[4]、Jupyter Notebook[5]

  • • 实验日志过程:Qwen2-1.5B-NER-Fintune - SwanLab[6]

  • • 模型:Modelscope

  • • 数据集:chinese_ner_sft

  • • SwanLab:https://swanlab.cn

知识点1:什么是指令微调?

大模型指令微调(Instruction Tuning)是一种针对大型预训练语言模型的微调技术,其核心目的是增强模型理解和执行特定指令的能力,使模型能够根据用户提供的自然语言指令准确、恰当地生成相应的输出或执行相关任务。

指令微调特别关注于提升模型在遵循指令方面的一致性和准确性,从而拓宽模型在各种应用场景中的泛化能力和实用性。

在实际应用中,我的理解是,指令微调更多把LLM看作一个更智能、更强大的传统NLP模型(比如Bert),来实现更高精度的NLP任务。所以这类任务的应用场景覆盖了以往NLP模型的场景,甚至很多团队拿它来标注互联网数据

知识点2:什么是命名实体识别?

命名实体识别 (NER) 是一种NLP技术,主要用于识别和分类文本中提到的重要信息(关键词)。这些实体可以是人名、地名、机构名、日期、时间、货币值等等。NER 的目标是将文本中的非结构化信息转换为结构化信息,以便计算机能够更容易地理解和处理。

6835fe007c37ae9f2540933d4c936f7a.jpeg

NER 也是一项非常实用的技术,包括在互联网数据标注、搜索引擎、推荐系统、知识图谱、医疗保健等诸多领域有广泛应用。

1.环境安装

本案例基于Python>=3.8,请在您的计算机上安装好Python,并且有一张英伟达显卡(显存要求并不高,大概10GB左右就可以跑)。

我们需要安装以下这几个Python库,在这之前,请确保你的环境内已安装好了pytorch以及CUDA:

  1. swanlab
  2. modelscope
  3. transformers
  4. datasets
  5. peft
  6. accelerate
  7. pandas

一键安装命令:

pip install swanlab modelscope transformers datasets peft pandas accelerate

本案例测试于modelscope==1.14.0、transformers==4.41.2、datasets==2.18.0、peft==0.11.1、accelerate==0.30.1、swanlab==0.3.11

2.准备数据集

本案例使用的是HuggingFace上的chinese_ner_sft数据集,该数据集主要被用于训练命名实体识别模型。

be6cf2ac24bb1f03057878e6aa2508dd.jpeg

chinese_ner_sft由不同来源、不同类型的几十万条数据组成,应该是我见过收录最齐全的中文NER数据集。

这次训练我们不需要用到它的全部数据,只取其中的CCFBDCI数据集(中文命名实体识别算法鲁棒性评测数据集)进行训练,该数据集包含LOC(地点)、GPE(地理)、ORG(组织)和PER(人名)四种实体类型标注,每条数据的例子如下:

  1. {
  2.   'text':'今天亚太经合组织第十二届部长级会议在这里开幕,中国外交部部长唐家璇、外经贸部部长石广生出席了会议。',
  3. 'entities':[
  4. {
  5. 'start_idx':23,
  6. 'end_idx':25,
  7. 'entity_text':'中国',
  8. 'entity_label':'GPE',
  9. 'entity_names':['地缘政治实体','政治实体','地理实体','社会实体']},
  10. {
  11. 'start_idx':25,
  12. 'end_idx':28,
  13. 'entity_text':'外交部',
  14. 'entity_label':'ORG',
  15. 'entity_names':['组织','团体','机构']
  16. },
  17. {
  18. 'start_idx':30,
  19. 'end_idx':33,
  20. 'entity_text':'唐家璇',
  21. 'entity_label':'PER',
  22. 'entity_names':['人名','姓名']
  23. },
  24. ...
  25. ],
  26. 'data_source':'CCFBDCI'
  27. }

其中text是输入的文本,entities是文本抽取出的实体。我们的目标是希望微调后的大模型能够根据由text组成的提示词,预测出一个json格式的实体信息:

  1. 输入:今天亚太经合组织第十二届部长级会议在这里开幕,中国外交部部长唐家璇、外经贸部部长石广生出席了会议。
  2. 大模型输出:{'entity_text':'中国', 'entity_label':'组织'}{'entity_text':'唐家璇', 'entity_label':'人名'}...

现在我们将数据集下载到本地目录。下载方式是前往chinese_ner_sft - huggingface下载ccfbdci.jsonl到项目根目录下即可:

1b7360aefb8f993831d57263bda7dbda.jpeg

3. 加载模型

这里我们使用modelscope下载Qwen2-1.5B-Instruct模型(modelscope在国内,所以直接用下面的代码自动下载即可,不用担心速度和稳定性问题),然后把它加载到Transformers中进行训练:

  1. from modelscope import snapshot_download,AutoTokenizer
  2. from transformers importAutoModelForCausalLM,TrainingArguments,Trainer,DataCollatorForSeq2Seq
  3. model_id ='qwen/Qwen2-1.5B-Instruct'
  4. model_dir ='./qwen/Qwen2-1___5B-Instruct'
  5. # 在modelscope上下载Qwen模型到本地目录下
  6. model_dir = snapshot_download(model_id, cache_dir='./', revision='master')
  7. # Transformers加载模型权重
  8. tokenizer =AutoTokenizer.from_pretrained(model_dir, use_fast=False, trust_remote_code=True)
  9. model =AutoModelForCausalLM.from_pretrained(model_dir, device_map='auto', torch_dtype=torch.bfloat16)
  10. model.enable_input_require_grads()  # 开启梯度检查点时,要执行该方法

4. 配置训练可视化工具

我们使用SwanLab来监控整个训练过程,并评估最终的模型效果。

这里直接使用SwanLab和Transformers的集成来实现:

  1. from swanlab.integration.huggingface import SwanLabCallback
  2. swanlab_callback = SwanLabCallback(...)
  3. trainer = Trainer(
  4.     ...
  5.     callbacks=[swanlab_callback],
  6. )

如果你是第一次使用SwanLab,那么还需要去https://swanlab.cn上注册一个账号,在用户设置页面复制你的API Key,然后在训练开始时粘贴进去即可:

e348f5156b0697e89279b068ad7f60d0.jpeg

5. 完整代码

开始训练时的目录结构:

  1. |--- train.py
  2. |--- ccfbdci.jsonl

train.py:

  1. import json
  2. import pandas as pd
  3. import torch
  4. from datasets importDataset
  5. from modelscope import snapshot_download,AutoTokenizer
  6. from swanlab.integration.huggingface importSwanLabCallback
  7. from peft importLoraConfig,TaskType, get_peft_model
  8. from transformers importAutoModelForCausalLM,TrainingArguments,Trainer,DataCollatorForSeq2Seq
  9. import os
  10. import swanlab
  11. def dataset_jsonl_transfer(origin_path, new_path):
  12. '''
  13.     将原始数据集转换为大模型微调所需数据格式的新数据集
  14.     '''
  15.     messages =[]
  16. # 读取旧的JSONL文件
  17. with open(origin_path,'r')as file:
  18. for line in file:
  19. # 解析每一行的json数据
  20.             data = json.loads(line)
  21.             input_text = data['text']
  22.             entities = data['entities']
  23.             match_names =['地点','人名','地理实体','组织']
  24.             entity_sentence =''
  25. for entity in entities:
  26.                 entity_json = dict(entity)
  27.                 entity_text = entity_json['entity_text']
  28.                 entity_names = entity_json['entity_names']
  29. for name in entity_names:
  30. if name in match_names:
  31.                         entity_label = name
  32. break
  33.                 entity_sentence += f'''{{'entity_text': '{entity_text}', 'entity_label': '{entity_label}'}}'''
  34. if entity_sentence =='':
  35.                 entity_sentence ='没有找到任何实体'
  36.             message ={
  37. 'instruction':'''你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如 {'entity_text': '南京', 'entity_label': '地理实体'} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出'没有找到任何实体'. ''',
  38. 'input': f'文本:{input_text}',
  39. 'output': entity_sentence,
  40. }
  41.             messages.append(message)
  42. # 保存重构后的JSONL文件
  43. with open(new_path,'w', encoding='utf-8')as file:
  44. for message in messages:
  45.             file.write(json.dumps(message, ensure_ascii=False)+'\n')
  46. def process_func(example):
  47. '''
  48.     将数据集进行预处理
  49.     '''
  50.     MAX_LENGTH =384
  51.     input_ids, attention_mask, labels =[],[],[]
  52.     system_prompt ='''你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如 {'entity_text': '南京', 'entity_label': '地理实体'} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出'没有找到任何实体'.'''
  53.     instruction = tokenizer(
  54.         f'<|im_start|>system\n{system_prompt}<|im_end|>\n<|im_start|>user\n{example['input']}<|im_end|>\n<|im_start|>assistant\n',
  55.         add_special_tokens=False,
  56. )
  57.     response = tokenizer(f'{example['output']}', add_special_tokens=False)
  58.     input_ids = instruction['input_ids']+ response['input_ids']+[tokenizer.pad_token_id]
  59.     attention_mask =(
  60.         instruction['attention_mask']+ response['attention_mask']+[1]
  61. )
  62.     labels =[-100]* len(instruction['input_ids'])+ response['input_ids']+[tokenizer.pad_token_id]
  63. if len(input_ids)> MAX_LENGTH:# 做一个截断
  64.         input_ids = input_ids[:MAX_LENGTH]
  65.         attention_mask = attention_mask[:MAX_LENGTH]
  66.         labels = labels[:MAX_LENGTH]
  67. return{'input_ids': input_ids,'attention_mask': attention_mask,'labels': labels}
  68. def predict(messages, model, tokenizer):
  69.     device ='cuda'
  70.     text = tokenizer.apply_chat_template(
  71.         messages,
  72.         tokenize=False,
  73.         add_generation_prompt=True
  74. )
  75.     model_inputs = tokenizer([text], return_tensors='pt').to(device)
  76.     generated_ids = model.generate(
  77.         model_inputs.input_ids,
  78.         max_new_tokens=512
  79. )
  80.     generated_ids =[
  81.         output_ids[len(input_ids):]for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
  82. ]
  83.     response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
  84. print(response)
  85. return response
  86. model_id ='qwen/Qwen2-1.5B-Instruct'
  87. model_dir ='./qwen/Qwen2-1___5B-Instruct'
  88. # 在modelscope上下载Qwen模型到本地目录下
  89. model_dir = snapshot_download(model_id, cache_dir='./', revision='master')
  90. # Transformers加载模型权重
  91. tokenizer =AutoTokenizer.from_pretrained(model_dir, use_fast=False, trust_remote_code=True)
  92. model =AutoModelForCausalLM.from_pretrained(model_dir, device_map='auto', torch_dtype=torch.bfloat16)
  93. model.enable_input_require_grads()# 开启梯度检查点时,要执行该方法
  94. # 加载、处理数据集和测试集
  95. train_dataset_path ='ccfbdci.jsonl'
  96. train_jsonl_new_path ='ccf_train.jsonl'
  97. ifnot os.path.exists(train_jsonl_new_path):
  98.     dataset_jsonl_transfer(train_dataset_path, train_jsonl_new_path)
  99. # 得到训练集
  100. total_df = pd.read_json(train_jsonl_new_path, lines=True)
  101. train_df = total_df[int(len(total_df)*0.1):]
  102. train_ds =Dataset.from_pandas(train_df)
  103. train_dataset = train_ds.map(process_func, remove_columns=train_ds.column_names)
  104. config =LoraConfig(
  105.     task_type=TaskType.CAUSAL_LM,
  106.     target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],
  107.     inference_mode=False,# 训练模式
  108.     r=8,# Lora 秩
  109.     lora_alpha=32,# Lora alaph,具体作用参见 Lora 原理
  110.     lora_dropout=0.1,# Dropout 比例
  111. )
  112. model = get_peft_model(model, config)
  113. args =TrainingArguments(
  114.     output_dir='./output/Qwen2-NER',
  115.     per_device_train_batch_size=4,
  116.     per_device_eval_batch_size=4,
  117.     gradient_accumulation_steps=4,
  118.     logging_steps=10,
  119.     num_train_epochs=2,
  120.     save_steps=100,
  121.     learning_rate=1e-4,
  122.     save_on_each_node=True,
  123.     gradient_checkpointing=True,
  124.     report_to='none',
  125. )
  126. swanlab_callback =SwanLabCallback(
  127.     project='Qwen2-NER-fintune',
  128.     experiment_name='Qwen2-1.5B-Instruct',
  129.     description='使用通义千问Qwen2-1.5B-Instruct模型在NER数据集上微调,实现关键实体识别任务。',
  130.     config={
  131. 'model': model_id,
  132. 'model_dir': model_dir,
  133. 'dataset':'qgyd2021/chinese_ner_sft',
  134. },
  135. )
  136. trainer =Trainer(
  137.     model=model,
  138.     args=args,
  139.     train_dataset=train_dataset,
  140.     data_collator=DataCollatorForSeq2Seq(tokenizer=tokenizer, padding=True),
  141.     callbacks=[swanlab_callback],
  142. )
  143. trainer.train()
  144. # 用测试集的随机20条,测试模型
  145. # 得到测试集
  146. test_df = total_df[:int(len(total_df)*0.1)].sample(n=20)
  147. test_text_list =[]
  148. for index, row in test_df.iterrows():
  149.     instruction = row['instruction']
  150.     input_value = row['input']
  151.     messages =[
  152. {'role':'system','content': f'{instruction}'},
  153. {'role':'user','content': f'{input_value}'}
  154. ]
  155.     response = predict(messages, model, tokenizer)
  156.     messages.append({'role':'assistant','content': f'{response}'})
  157.     result_text = f'{messages[0]}\n\n{messages[1]}\n\n{messages[2]}'
  158.     test_text_list.append(swanlab.Text(result_text, caption=response))
  159. swanlab.log({'Prediction': test_text_list})
  160. swanlab.finish()

看到下面的进度条即代表训练开始:

729398e22be08c14f408b439903c7bb6.jpeg

5.训练结果演示

在SwanLab上查看最终的训练结果:

可以看到在2个epoch之后,微调后的qwen2的loss降低到了不错的水平——当然对于大模型来说,真正的效果评估还得看主观效果。

66c970c92e876da78cd976d95cc8ec59.jpeg

可以看到在一些测试样例上,微调后的qwen2能够给出准确的实体抽取结果:

f715722b5e690643b7d113e145fcd4ec.jpeg 9a49c6ec03998e66daed3f4aff079ce3.jpeg

至此,你已经完成了qwen2指令微调的训练!

6. 推理训练好的模型

训好的模型默认被保存在./output/Qwen2-NER文件夹下。

推理模型的代码如下:

  1. import torch
  2. from transformers importAutoModelForCausalLM,AutoTokenizer
  3. from peft importPeftModel
  4. def predict(messages, model, tokenizer):
  5.     device ='cuda'
  6.     text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
  7.     model_inputs = tokenizer([text], return_tensors='pt').to(device)
  8.     generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
  9.     generated_ids =[output_ids[len(input_ids):]for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)]
  10.     response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
  11. return response
  12. # 加载原下载路径的tokenizer和model
  13. tokenizer =AutoTokenizer.from_pretrained('./qwen/Qwen2-1___5B-Instruct/', use_fast=False, trust_remote_code=True)
  14. model =AutoModelForCausalLM.from_pretrained('./qwen/Qwen2-1___5B-Instruct/', device_map='auto', torch_dtype=torch.bfloat16)
  15. # 加载训练好的Lora模型,将下面的[checkpoint-XXX]替换为实际的checkpoint文件名名称
  16. model =PeftModel.from_pretrained(model, model_id='./output/Qwen2-NER/checkpoint-1700')
  17. input_text ='西安电子科技大学的陈志明爱上了隔壁西北工业大学苏春红,他们约定好毕业后去中国的苏州定居。'
  18. test_texts ={
  19. 'instruction':'''你是一个文本实体识别领域的专家,你需要从给定的句子中提取 地点; 人名; 地理实体; 组织 实体. 以 json 格式输出, 如; {'entity_text': '南京', 'entity_label': '地理实体'} 注意: 1. 输出的每一行都必须是正确的 json 字符串. 2. 找不到任何实体时, 输出'没有找到任何实体'. ''',
  20. 'input': f'文本:{input_text}'
  21. }
  22. instruction = test_texts['instruction']
  23. input_value = test_texts['input']
  24. messages =[
  25. {'role':'system','content': f'{instruction}'},
  26. {'role':'user','content': f'{input_value}'}
  27. ]
  28. response = predict(messages, model, tokenizer)
  29. print(response)

输出结果为:

  1. {'entity_text':'西安电子科技大学','entity_label':'组织'}
  2. {'entity_text':'陈志明','entity_label':'人名'}
  3. {'entity_text':'西北工业大学','entity_label':'组织'}
  4. {'entity_text':'苏春红','entity_label':'人名'}
  5. {'entity_text':'中国','entity_label':'地理实体'}
  6. {'entity_text':'苏州','entity_label':'地理实体'}
引用链接

[1] Qwen2: https://modelscope.cn/models/qwen/Qwen2-1.5B-Instruct/summary
[2] 中文NER: https://huggingface.co/datasets/qgyd2021/chinese_ner_sft
[3] SwanLab: https://swanlab.cn/
[4] Github: https://github.com/Zeyi-Lin/LLM-Finetune
[5] Jupyter Notebook: https://github.com/Zeyi-Lin/LLM-Finetune/blob/main/notebook/train_qwen2_ner.ipynb
[6] Qwen2-1.5B-NER-Fintune - SwanLab: https://swanlab.cn/@ZeyiLin/Qwen2-NER-fintune/runs/9gdyrkna1rxjjmz0nks2c/chart


备注:昵称-学校/公司-方向/会议(eg.ACL),进入技术/投稿群

9cafe1ea116999d2209f2c1e82eef2d2.png

id:DLNLPer,记得备注呦

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/793543
推荐阅读
相关标签
  

闽ICP备14008679号