开源模型应用落地-KnowLM模型小试-入门篇(一)

一、前言

     你是否了解知识图谱?如果了解,你们的业务场景是否应用了知识图谱?实际上,知识图谱在各行各业都被广泛使用。例如,在搜索引擎优化方面,通过利用知识图谱,搜索引擎可以更好地理解网页内容之间的关系,从而提高搜索结果的准确性和相关性。在医药领域,知识图谱可以整合医学知识和临床数据,辅助医生进行诊断和治疗决策,并提供个性化的医疗建议和健康管理服务。

    接下来我们将进一步探讨如何利用开源的大型语言模型,以更好地进行知识提取。


二、术语

    2.1. 知识图谱

    是一种结构化的知识表示方式,用于描述现实世界中的实体和它们之间的关系。它是一种用于组织和表示知识的图形模型,其中的实体和关系被表示为节点和边。

    知识图谱使用的常见业务场景:

  • 搜索引擎优化(SEO):知识图谱可以帮助搜索引擎理解网页内容之间的关系,提高搜索结果的准确性和相关性。
  • 问答系统:知识图谱可以用于构建智能问答系统,使用户能够通过提问获取准确的答案,而不仅仅是关键词匹配。
  • 个性化推荐:知识图谱可以分析用户的兴趣、喜好和行为,并为用户提供个性化的推荐内容,例如商品推荐、新闻推荐等。
  • 智能客服:知识图谱可以用于构建智能客服系统,通过理解用户问题和上下文,提供准确的答案或引导用户解决问题。
  • 企业知识管理:知识图谱可以整合和管理企业内部的大量知识和信息,提供快速的搜索、浏览和分享功能,促进知识的共享和协作。
  • 智能助理:知识图谱可以作为智能助理的核心,帮助用户管理日程安排、获取有用信息、执行任务等。
  • 数据分析和决策支持:知识图谱可以用于整合和分析大量的结构化和非结构化数据,帮助企业做出更准确的决策和预测。
  • 医疗健康:知识图谱可以整合医学知识和临床数据,辅助医生进行诊断和治疗决策,提供个性化的医疗建议和健康管理服务。
  • 金融风控:知识图谱可以整合各种金融数据和信息,帮助金融机构进行风险评估、欺诈检测和信用评级等业务。
  • 社交网络分析:知识图谱可以分析社交网络中的关系和行为模式,帮助企业和组织发现潜在的合作伙伴、影响者和市场机会。

    2.2. 实体

    是知识图谱中的核心概念,代表现实世界中的具体或抽象事物。实体可以是人、地点、事件、概念等等。每个实体在知识图谱中通常由一个唯一的标识符表示。例如,在一个包含音乐相关知识的图谱中,歌手、专辑、歌曲可以作为实体。

    2.3. 关系

    指的是实体之间的连接或相互作用。关系描述了实体之间的某种关联、依赖、属性等。关系可以是有向的或无向的,可以是单值的或多值的。例如,在一个社交网络的知识图谱中,"朋友"关系可以连接一个人实体和另一个人实体,描述他们之间的友谊关系。

    2.4. KnowLM

    是由浙江大学NLP&KG团队的在读博士生研发并开源的项目,是一种将LLM与知识图谱结合的知识抽取大模型,主要包含的任务有命名实体识别(NER)、事件抽取(EE)、关系抽取(RE)。github 地址:https://github.com/zjunlp/KnowLM/blob/main/README_ZH.md


这是KnowLM框架的总览图。主要有三个技术特色:

1.知识提示:基于知识图谱等结构化数据的知识提示生成和知识增强约束技术,解决知识抽取和推理问题

2.知识编辑:基于知识编辑技术对齐大模型内过时、错误及价值观不正确的知识,解决知识谬误问题 (英文版Tutorial)

3.知识交互:基于知识动态交互和反馈实现工具组合学习及多智能体协作,解决大模型具身认知问题 (英文版Tutorial)


三、前置条件

3.1. 下载模型文件

    # 基础模型

    https://huggingface.co/zjunlp/knowlm-7b-base/tree/main

   

    # 对话模型

    https://huggingface.co/zjunlp/knowlm-7b-chat/tree/main

    

    PS:

    1) 从huggingface中下载

    2) modelscope没有对应模型,需要下载其他版本,例如:git clone https://www.modelscope.cn/ZJUNLP/knowlm-13b-ie.git

3.2. windows操作系统(内存≥32GB)

3.3. 安装环境

    1) conda create -n knowlm python=3.10 -y

    2) conda activate knowlm

    3) pip install torch  -i https://pypi.tuna.tsinghua.edu.cn/simple

    4) pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

    PS:

    1)requirements.txt文件内容如下(要安装特定版本,需要指定版本号):

        bitsandbytes
        datasets
        sentencepiece
        fire
        accelerate
        transformers
        peft


四、技术实现

4.1. 加载tokenizer

tokenizer = LlamaTokenizer.from_pretrained(modelPath)

4.2.加载model

model = LlamaForCausalLM.from_pretrained(modelPath, device_map="cpu",low_cpu_mem_usage=True).eval()

4.3.推理(非流式输出)

generation_output = model.generate(
        input_ids=input_ids,
        generation_config=generation_config,
        return_dict_in_generate=True,
        output_scores=True,
        max_new_tokens=8192,
    )
s = generation_output.sequences[0]
output = tokenizer.decode(s)

4.4.完整代码

# -*-  coding = utf-8 -*-
import torch
from transformers import GenerationConfig, LlamaForCausalLM, LlamaTokenizer
import time

modelPath = "E:\\model\\knowlm-7b-chat"

response_split =  "### Response:"

def get_response(output: str) -> str:
    result = output.split(response_split)[1].strip()
    result = result.replace('</s>', '')
    return result

def generate(model,tokenizer,message,generation_config):
    s_format = "{'head':'', 'relation':'', 'tail':''}"
    instruction = f"""
        Please find the possible head entities (subjects) and tail entities (objects) in the text and give the corresponding relation triples. Please format your answer as a list of relation triples in the form of {s_format}.
         """
    prompt = generate_prompt_input(instruction,message)
    inputs = tokenizer(prompt, return_tensors="pt")

    if torch.cuda.is_available():
        input_ids = inputs["input_ids"].to('cuda')
    else:
        input_ids = inputs["input_ids"]

    generation_output = model.generate(
        input_ids=input_ids,
        generation_config=generation_config,
        return_dict_in_generate=True,
        output_scores=True,
        max_new_tokens=8192,
    )
    s = generation_output.sequences[0]
    output = tokenizer.decode(s)
    return get_response(output)

# Generate the prompt for the input of LM model
def generate_prompt_no_input(instruction):
    return f"""
Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{instruction}

### Response:
"""

def generate_prompt_input(instruction,input):
    return f"""
Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction:
{instruction}

### Input:
{input}

### Response:
"""


def loadTokenizer():
    tokenizer = LlamaTokenizer.from_pretrained(modelPath)
    return tokenizer

def loadModel():
    model = LlamaForCausalLM.from_pretrained(modelPath, device_map="cpu",low_cpu_mem_usage=True).eval()

    return model

if __name__ == '__main__':
    model = loadModel()
    tokenizer = loadTokenizer()
    start_time = time.time()

    generation_config = GenerationConfig.from_pretrained(modelPath, trust_remote_code=True)  # 可指定不同的生成长度、top_p等相关超参
    message = "Zhang San and I are good friends. This Friday, we went to visit a museum together"
    response = generate(model,tokenizer,message,generation_config)
    print(f'response: {response}')

    end_time = time.time()
    print("执行耗时: {:.2f}秒".format(end_time-start_time))

4.5.程序输出


五、附带说明

5.1. KnowLM项目自带的prompt模板

    relation_template =  {
		0:'已知候选的关系列表:{s_schema},请你根据关系列表,从以下输入中抽取出可能存在的头实体与尾实体,并给出对应的关系三元组。请按照{s_format}的格式回答。',
		1:'我将给你个输入,请根据关系列表:{s_schema},从输入中抽取出可能包含的关系三元组,并以{s_format}的形式回答。',
		2:'我希望你根据关系列表从给定的输入中抽取可能的关系三元组,并以{s_format}的格式回答,关系列表={s_schema}。',
		3:'给定的关系列表是:{s_schema}\n根据关系列表抽取关系三元组,在这个句子中可能包含哪些关系三元组?请以{s_format}的格式回答。',
	}

	relation_int_out_format = {
		0:['"(头实体,关系,尾实体)"', relation_convert_target0],
		2:['"关系:头实体,尾实体\n"', relation_convert_target2],
		3:["JSON字符串[{'head':'', 'relation':'', 'tail':''}, ]", relation_convert_target3],
	}


	en_relation_template = {
		0: 'Identify the head entities (subjects) and tail entities (objects) in the following text and provide the corresponding relation triples from relation list {s_schema}. Please provide your answer as a list of relation triples in the form of {s_format}.',
		1: 'Identify the subjects and objects in the text that are related, and provide the corresponding relation triples from relation {s_schema} in the format of {s_format}.',
		2: 'From the given text, extract the possible head entities (subjects) and tail entities (objects) and give the corresponding relation triples. The relations are {s_schema}. Please format your answer as a list of relation triples in the form of {s_format}.',
		3: 'Your task is to identify the head entities (subjects) and tail entities (objects) in the following text and extract the corresponding relation triples, the possible relation list is {s_schema}. Your answer should include relation triples, with each triple formatted as {s_format}.',
		4: 'Given the text, extract the possible head entities (subjects) and tail entities (objects) and provide the corresponding relation triples, the possible relation list is {s_schema}. Format your answer as a list of relation triples in the form of {s_format}.',
		5: 'Your goal is to identify the head entities (subjects) and tail entities (objects) in the text and give the corresponding relation triples. The given relation list is {s_schema}. Please answer with a list of relation triples in the form of {s_format}.',
		6: 'Please extract the possible head entities (subjects) and tail entities (objects) from the text and provide the corresponding relation triples from candidate relation list {s_schema}. Your answer should be in the form of a list of relation triples: {s_format}.',
		7: 'Your task is to extract the possible head entities (subjects) and tail entities (objects) in the given text and give the corresponding relation triples. The relations are {s_schema}. Please answer using the format of a list of relation triples: {s_format}.',
		8: 'Given the {s_schema}, identify the head entities (subjects) and tail entities (objects) and provide the corresponding relation triples. Your answer should consist of relation triples, with each triple formatted as {s_format}',
		9: 'Please find the possible head entities (subjects) and tail entities (objects) in the text based on the relation list {s_schema} and give the corresponding relation triples. Please format your answer as a list of relation triples in the form of {s_format}.',
		10: 'Given relation list {s_schema}, extract the possible subjects and objects from the text and give the corresponding relation triples in the format of {s_format}.',
		11: 'Extract the entities involved in the relationship described in the text and provide the corresponding triples in the format of {s_format}, the possible relation list is {s_schema}.',
		12: 'Given relation list {s_schema}, provide relation triples for the entities and their relationship in the text, using the format of {s_format}.',
		13: 'Extract the entities and their corresponding relationships from the given relationships are {s_schema} and provide the relation triples in the format of {s_format}.',
	}

	en_relation_int_out_format = {
		0: "{'head':'', 'relation':'', 'tail':''}",
		1: "(Subject, Relation, Object)",
		2: "[Subject, Relation, Object]",
		3: "{head, relation, tail}",
		4: "<head, relation, tail>",
	}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/344197.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【英文干货】【Word_Search】找单词游戏(第3天)

本期主题&#xff1a;Doors&#xff08;各式各样的门&#xff09; 本期单词&#xff1a; Automatic (Door) 自动门 Back (Door) 后门 Barn (Door) 谷仓的门 Battened (Door) 用木条加固的门 Fire (Door) 防火门 Front (Door) 前门 Garage (Door) 车库的门 Glazed (Door…

大数据学习之Flink算子、了解(Transformation)转换算子(基础篇三)

Transformation转换算子&#xff08;基础篇三&#xff09; 目录 Transformation转换算子&#xff08;基础篇三&#xff09; 三、转换算子&#xff08;Transformation&#xff09; 1.基本转换算子 1.1 映射&#xff08;Map&#xff09; 1.2 过滤&#xff08;filter&#xf…

【优先级队列 之 堆的实现】

文章目录 前言优先级队列 PriorityQueue优先队列的模拟实现 堆堆的储存方式堆的创建建堆的时间复杂度堆的插入与删除 总结 前言 优先级队列 PriorityQueue 概念&#xff1a;对列是先进先出的的数据结构&#xff0c;但有些情况&#xff0c;数据可能带有优先级&#xff0c;一般出…

C++:使用tinyXML生成矢量图svg

先说一下tinyXML库的配置&#xff1a; 很简单&#xff0c;去下面官网下载 TinyXML download | SourceForge.net 解压后是这样 直接将红框中的几个文件放到项目中即可使用 关于svg文件&#xff0c;SVG是基于XML的可扩展矢量图形&#xff0c;svg是xml文件&#xff0c;但是xml…

TCP三握四挥(面试需要)

TCP建立连接需要三次握手过程&#xff0c;关闭连接需要四次挥手过程 三次握手 从图中可以看出&#xff0c;客户端在发起connect时&#xff0c;会发起第一次和第三次握手。服务端在接收客户端连接时&#xff0c;会发起第二次握手。 这三次握手&#xff0c;都会通过SYNACK的方式…

阿里云4核8G云服务器价格、带宽及系统盘费用

阿里云服务器4核8g配置云服务器u1价格是955.58元一年&#xff0c;4核8G配置还可以选择ECS计算型c7实例、计算型c8i实例、计算平衡增强型c6e、ECS经济型e实例、AMD计算型c8a等机型等ECS实例规格&#xff0c;规格不同性能不同&#xff0c;价格也不同&#xff0c;阿里云服务器网al…

EasyExcel入门使用

EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。他能让你在不用考虑性能、内存的等因素的情况下&#xff0c;快速完成Excel的读、写等功能。 EasyExcel 的主要特点如下&#xff1a; 1、高性能&#xff1a;EasyExcel 采用了异步导入导出的方式&…

数据结构:搜索二叉树 | 红黑树 | 验证是否为红黑树

文章目录 1.红黑树的概述2.红黑树的性质3.红黑树的代码实现3.1.红黑树的节点定义3.2.红黑树的插入操作3.3.红黑树是否平衡 黑红树是一颗特殊的搜索二叉树&#xff0c;本文在前文的基础上&#xff0c;图解红黑树插入&#xff1a;前文 链接&#xff0c;完整对部分关键代码展示&a…

macOS跨进程通信: Unix Domain Socket 创建实例

macOS跨进程通信: Unix Domain Socket 创建实例 一&#xff1a; 简介 Socket 是 网络传输的抽象概念。 一般我们常用的有Tcp Socket和 UDP Scoket&#xff0c; 和类Unix 系统&#xff08;包括Mac&#xff09;独有的 Unix Domain Socket&#xff08;UDX&#xff09;。 Tcp So…

避雷!仅1天撤回55篇中国学者的研究论文!这本毕业神刊需要注意!

【SciencePub学术】 这本国际期刊&#xff0c;仅仅去年12月一个月的时间&#xff0c;就撤回了近60篇国人文章&#xff01;这本期刊就是来自Hindawi出版社的APPLIED BIONICS AND BIOMECHANICS。 01 期刊信息简介 APPLIED BIONICS AND BIOMECHANICS IF(2022)&#xff1a;2.2&…

三维城市模型提升日本的智慧城市管理

MicroStation 将工作效率提高 50%&#xff0c;实现了前所未有的逼真模拟 构建三维城市模型生态系统 PLATEAU 项目由日本国土交通省牵头&#xff0c;是一项三维城市模型和数字孪生计划&#xff0c;旨在到 2027 年为日本 500 个城市构建开放的城市模型数字生态系统。作为日本最…

java获取linux和window序列号

前言 获取系统序列号在Java中并不是一个直接支持的功能&#xff0c;因为Java语言本身并不提供直接访问硬件级别的信息&#xff0c;如CPU序列号。但是&#xff0c;我们可以使用一些平台特定的工具或命令来实现这一功能。下面我将展示如何使用Java获取Windows和Linux系统上的CPU…

通过代理服务器的方式解决跨域问题

学习源码可以看我的个人前端学习笔记 (github.com):qdxzw/frontlearningNotes 觉得有帮助的同学&#xff0c;可以点心心支持一下哈 这里以本地访问https://heimahr.itheima.net/api/sys/permission接口为列子 Node.js 代理服务器 (server.js) 本次考虑使用JSONP或CORS代理来…

PHP“引用”漏洞

今日例题&#xff1a; <?php highlight_file(__FILE__); error_reporting(0); include("flag.php"); class just4fun { var $enter; var $secret; } if (isset($_GET[pass])) { $pass $_GET[pass]; $passstr_replace(*,\*,$pass); } $o unser…

【操作系统】实验三 编译 Linux 内核

&#x1f57a;作者&#xff1a; 主页 我的专栏C语言从0到1探秘C数据结构从0到1探秘Linux &#x1f618;欢迎关注&#xff1a;&#x1f44d;点赞&#x1f64c;收藏✍️留言 &#x1f3c7;码字不易&#xff0c;你的&#x1f44d;点赞&#x1f64c;收藏❤️关注对我真的很重要&…

[Linux]HTTP状态响应码和示例

1xx&#xff1a;信息响应类&#xff0c;表示接收到请求并且继续处理 2xx&#xff1a;处理成功响应类&#xff0c;表示动作被成功接收、理解和接受 3xx&#xff1a;重定向响应类&#xff0c;为了完成指定的动作&#xff0c;必须接受进一步处理 4xx&#xff1a;客户端错误&#x…

如何使用Docker本地部署Jupyter Notebook并结合内网穿透实现远程访问

&#x1f4d1;前言 本文主要是Linux下通过使用Docker本地部署Jupyter Notebook并结合内网穿透实现远程访问的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是青衿&#x1f947; ☁️博客首页&#xff1a;…

单调栈笔记

单调栈 1.每日温度2.下一个更大元素 I3.下一个更大的元素4.接雨水5.柱状图中最大的矩形 单调栈正如其名字&#xff0c;用一个栈&#xff08;能够实现栈性质的数据结构就行&#xff09;来存储元素&#xff0c;存储在栈中的元素保持单调性&#xff08;单调递增或者是单调递减&…

Allegro如何设置飞线的显示方式?

预拉线最短化。 设置方法:选择菜单栏Setup→Design Parameters...(参数设置) 跳出下面对话框,根据需求设置。 Jogged:拼合的。 Straight:直的。 Closest endpoint:最靠近端点。 Pin to pin:引脚到引脚。 Jogged的显示效果。

MyBatis的逆向工程的创建,generator插件的使用和可能出现的一些问题,生成的实体类多出.java 1 .java 2这种拓展文件的处理方案

目录 创建逆向工程的步骤 ①添加依赖和插件 ②创建MyBatis的核心配置文件 ③创建逆向工程的配置文件 ④执行MBG插件的generate目标 数据库版本8有可能出现的问题&#xff1a; 1、生成的实体类多了.java 1 .java 2的拓展文件... 2、生成的属性与表中字段不匹配&#xff…