大模型相关目录
大模型,包括部署微调prompt/Agent应用开发、知识库增强、数据库增强、知识图谱增强、自然语言处理、多模态等大模型应用开发内容
从0起步,扬帆起航。
- 基于Dify的智能分类方案:大模型结合KNN算法(附代码)
- OpenCompass:大模型测评工具
- 一文读懂多模态大模型基础架构
- 大模型管理平台:one-api使用指南
- 大模型RAG、ROG、RCG概念科普
- RAGOnMedicalKG:大模型结合知识图谱的RAG实现
- DSPy:变革式大模型应用开发
- 最简明的Few-shot Prompt指南
- Semantic Kernel:微软大模型开发框架——LangChain 替代
- 对话大模型Prompt是否需要礼貌点?
- swift与Internvl下的多模态大模型分布式微调指南(附代码和数据)
- 多模态大模型Internvl-1.5-26B微调后部署及测试实录(附代码)
- 多模态大模型Internvl-2-26B的OCR赋能方案(附代码)
- miniconda+xinference的大模型推理部署指南
- Mem0:大模型最强赋能“有记忆的LLM”
- 再谈Agent:Dify智能体实现Txet2SQL
- Moe模式:或将是最好的大模型应用开发路径
文章目录
- 大模型相关目录
- 简介
- 实战
- 总结
简介
MOE(Mixture of Experts,混合专家)是一种机器学习模型架构,旨在通过结合多个专家网络来提高模型的性能和泛化能力。以下是传统模型和大模型中MOE模式的相关介绍及其优势。
传统模型中的MOE
在传统模型中,MOE通常由以下几个部分组成:
- Gate网络:决定输入数据应该被路由到哪一个专家网络。Gate网络可以根据输入数据的特征来动态分配数据。
- Expert网络:一系列专门的网络,每个网络都是针对特定数据分布进行训练的。Expert网络可以是对特定问题有深入理解的小模型。
- 组合层:将所有Expert网络的输出进行组合,形成最终的预测结果。
优势
- 提高泛化能力:不同的Expert可以学习数据的不同方面,从而提高模型对未知数据的泛化能力。
- 降低计算成本:不是所有Expert都会处理每个输入,Gate可以根据需要激活特定的Expert,这可以减少计算资源的使用。
- 灵活性强:可以很容易地通过增加或减少Expert来调整模型的大小和复杂度。
通俗地来讲,大模型中的MOE可以处理更加多样化的任务和数据类型进而提升应用效果,因为每个Expert都可以专注于不同的子任务或数据模式。简单地看,moe模式下的大模型应用开发本质上是对任务进行拆解,用大模型、小模型分工完成的一种思路。
实战
大部分代码参考文章:
https://blog.csdn.net/qq_43128256/article/details/140472280
该文章使用多模态大模型对人员学历信息进行ocr赋能,其中,绝大部分字段表现较好,精度如下:
人员姓名、学历层次识别准确率100%;性别识别准确率99.17%;专业识别准确率95.86%;毕业院校识别准确率92.56%;出生日期识别准确率90.91%毕业日期识别准确率88.42%;证件编号识别准确率36.3%
.
可见,对于长编码的阿拉伯字符串内容识别,多模态大模型存在较大问题,因此有必要引入moe机制,使用传统小模型对内容进行处理。
代码:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import functions as fc
import json
import os
from config import *
import base64
from openai import OpenAI
import openai
import pandas as pd
from paddleocr import PaddleOCR
# Paddleocr目前支持的多语言语种可以通过修改lang参数进行切换
# 例如`ch`, `en`, `fr`, `german`, `korean`, `japan`
ocr = PaddleOCR(use_angle_cls=True, lang="ch") # need to run only once to download and load model into memory
Conf = Config()
configs = Conf.get_config()
ocr_result_path = configs.ocr_result_path
second_path = configs.second_path # mid
# In[2]:
def get_ocr_result(img_path):
result = ocr.ocr(img_path, cls=False)
return result
def save_list_as_jsonl(data_list, file_path):
"""
将列表存储为JSONL格式的文件。
参数:
data_list -- 要存储的列表。
file_path -- 输出文件的路径。
"""
with open(file_path, 'w', encoding='utf-8') as f:
for item in data_list:
json_line = json.dumps(item, ensure_ascii=False)
f.write(json_line + '\n')
def read_jsonl(file_path):
"""
读取JSONL格式的文件,并将每一行解析为一个Python对象。
参数:
file_path -- 要读取的JSONL文件的路径。
返回:
一个列表,包含文件中每一行解析后的Python对象。
"""
data_list = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
data_list.append(json.loads(line))
return data_list
def get_llm_ocr_response(input_text):
client = openai.Client(api_key='YOUR_API_KEY', base_url='http://172.20.32.127:12335/v1')
# 确保获取模型ID的代码是正确的
models = client.models.list()
if not models.data:
print("No models found.")
return
model_name = models.data[0].id
try:
response = client.chat.completions.create(
model=model_name,
messages=[
{
"role": "system",
"content": "## 职位:你是一个信息抽取专家,可从原始文字信息中提取证书编号,并输出json格式化的识别结果"
},
{
"role": "user",
"content": f"原始文字信息:\n{input_text}\n" + '''
你需要从原始文字信息中提取证书编号,提取后返回的json格式参考如下:
{
"证书编号":"162391201905007614"
}
注意,提取不到时将提取内容标注“null”。
注意,我不需要任何代码,请输出json格式结果,json严格按照上述格式。
'''
}
],
temperature=0,
top_p=1
)
answer = response.choices[0].message.content
print(answer)
return answer
except openai.error.BadRequestError as e:
print(f"Error: {e}")
print(f"Error details: {e.details}")
def get_elements_with_string(lst, target_string):
return [element for element in lst if target_string in element]
def read_json_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except FileNotFoundError:
return "文件未找到。请检查文件路径是否正确。"
except json.JSONDecodeError:
return "文件内容不是有效的JSON。"
except Exception as e:
return f"读取文件时发生错误: {e}"
# In[3]:
file_paths = fc.list_files_with_absolute_paths(r'C:\Users\12258\Desktop\hy-vLLM\rysb\singel_code_test\code')
ocr_results = []
for file_path in file_paths:
print('OCR正在识别:',file_path)
ocr_result = get_ocr_result(file_path)
ocr_results.append({file_path.split('\\')[-1]:ocr_result})
# In[4]:
save_list_as_jsonl(ocr_results,'single_ocr_results.jsonl')
# In[15]:
ocr_results = read_jsonl('single_ocr_results.jsonl')
ocr_dict = {}
for orc_result in ocr_results:
ocr_dict[list(orc_result.keys())[0]] = list(orc_result.values())[0]
file_paths = fc.list_files_with_absolute_paths(second_path)
current_path = os.getcwd()
ocr_json_path = os.path.join(current_path, "single_ocr_json")
fc.create_directory(ocr_json_path)
for k,v in ocr_dict.items():
# try:
print(k)
ocr_response = get_llm_ocr_response(v)
data_dict = json.loads(fc.post_processing(ocr_response).replace('\\n','').replace('\\',''))
fc.save_json_to_file(data_dict,ocr_json_path+'\\'+k.split('\\')[-1].split('.')[0]+'.json')
# except Exception as e:
# current_time_str = configs.now_time_str
# fc.error_log('json save error!'+' '+k+' '+current_time_str)
# print(f"保存JSON数据时发生错误: {e}")
# In[29]:
mid_excel_path = r"C:\Users\12258\Desktop\hy-vLLM\rysb\singel_code_test\已核对 - 副本.xlsx"
name_set = pd.read_excel(mid_excel_path)['学生姓名'].tolist()
file_absolute_paths = fc.list_files_with_absolute_paths(r'C:\Users\12258\Desktop\hy-vLLM\rysb\student_infos_process_V20240715\single_ocr_json')
finall_json_ls = []
for name in name_set:
#对于每个学生,定位其名下所有文件
mid_file_paths = get_elements_with_string(file_absolute_paths,name)
zhuanke_files = get_elements_with_string(mid_file_paths,'专')
len_zhuanke_files = len(zhuanke_files)
benke_files = get_elements_with_string(mid_file_paths,'本科')
len_benke_files = len(benke_files)
shuoshi_files = get_elements_with_string(mid_file_paths,'硕士')
len_shuoshi_files = len(shuoshi_files)
yanjiusheng_files = get_elements_with_string(mid_file_paths,'研究生')
len_yanjiusheng_files = len(yanjiusheng_files)
boshi_files = get_elements_with_string(mid_file_paths,'博士')
len_boshi_files = len(boshi_files)
error_flag = len_zhuanke_files+len_benke_files+len_shuoshi_files+len_yanjiusheng_files+len_boshi_files
# print(name,error_flag)
if error_flag == 0:
current_time_str = configs.now_time_str
print(name,'file name error!')
fc.error_log('file name error!'+' '+name+' '+current_time_str)
else:
if len_boshi_files:
mid_file = get_elements_with_string(boshi_files,'毕业')
if len(mid_file) == 0:
pass
else:
finall_json_ls.append(mid_file[0])
continue
if yanjiusheng_files+shuoshi_files:
mid_file = get_elements_with_string(yanjiusheng_files+shuoshi_files,'毕业')
if len(mid_file) == 0:
finall_json_ls.append((yanjiusheng_files+shuoshi_files)[0])
continue
else:
finall_json_ls.append(mid_file[0])
continue
if len_benke_files:
mid_file = get_elements_with_string(benke_files,'毕业')
if len(mid_file) == 0:
finall_json_ls.append((benke_files)[0])
continue
else:
finall_json_ls.append(mid_file[0])
continue
if len_zhuanke_files:
mid_file = get_elements_with_string(zhuanke_files,'毕业')
if len(mid_file) == 0:
finall_json_ls.append((zhuanke_files)[0])
continue
else:
finall_json_ls.append(mid_file[0])
continue
name_ls = []
sex_ls = []
birthday_ls = []
qualification_ls = []
time_ls = []
school_ls = []
major_ls = []
code_ls = []
for finall_json in finall_json_ls:
extract_flag = 0
single_json_data = read_json_file(finall_json)
try:
code_ls.append(single_json_data['证书编号'].replace(' ',''))
except:
extract_flag = 1
code_ls.append('null')
if extract_flag:
current_time_str = configs.now_time_str
print(finall_json,'file extract format error!')
fc.error_log('file extract format error!'+' '+finall_json+' '+current_time_str)
import pandas as pd
result_dict = {
'证书编号':code_ls
}
pd.DataFrame(result_dict).to_excel('ocr_code_result.xlsx',index=False)
# In[34]:
mid_excel_path = r"C:\Users\12258\Desktop\hy-vLLM\rysb\已核对.xlsx"
list1 = pd.read_excel(mid_excel_path)['证书编号'].tolist()
list2 = pd.read_excel(mid_excel_path)['MOE策略证书编号'].tolist()
n = 0
for index in range(len(list1)):
if str(list1[index]) == str(list2[index]):
n+=1
# ### single_OCR_test
# In[16]:
file_paths = fc.list_files_with_absolute_paths(r'C:\Users\12258\Desktop\hy-vLLM\rysb\student_infos_process_V20240715\single_ocr_json')
names = []
codes = []
for file_path in file_paths:
mid_data = read_json_file(file_path)['证书编号']
names.append(file_path.split('\\')[-1].split('.')[0])
codes.append(mid_data)
import pandas as pd
result_dict = {
'姓名':names,
'证书编号':codes
}
pd.DataFrame(result_dict).to_excel('single_ocr_code_result.xlsx',index=False)
最终该字段精度提升至88%+,该方案的成功表面大模型moe模式下应用具有落地条件。
总结
事实上,moe开发中,对于传统模型还尝试了其他的子方案,内容如下:
针对长编码字段识别研究情况:
1.多模态模型端到端识别多字段,准确度:36.3%
2.多模态模型端到端识别长编码字段单字段,准确度:44.6%
3.OCR识别卡证整体+文本大模型,准确度:83%
4.OCR识别卡证长编码字段局部+文本大模型:88%
5.OCR识别结果作为prompt+多模态大模型:86.3%
希望以上的内容能给研究中的同志、朋友提供一定参考!