2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
This article mainly introduces the prompt of the large model and gives a practical tutorial. Even if you have no basic knowledge, you can still build a large model.
Content: The initial stage of cultivation method helps to condense and enhance internal strength, laying the foundation for subsequent cultivation.
Prompt means prompt engineering. In large language models, "prompt" refers to the input text or instructions provided by the user to the model to guide the model to generate the corresponding output. Prompt plays a vital role in interacting with the model, which affects the model's understanding, the accuracy of the answer, and the creativity of the content. The following are the main meanings and functions of prompt in large models:
a. Guided model generation:Prompt provides the initial information and direction needed for the model to generate a response or output. It can contain questions, instructions, keywords, or contextual information to help the model understand the user's intentions and needs and generate accordingly.
b. Contextual understanding: Through prompts, the model is able to understand the context of the current conversation or task. This is critical to ensure that the model generates responses that are relevant and coherent to user expectations, especially in long-term interactions or multi-round conversations.
c. Answer accuracy: A clear and detailed prompt usually leads to a more accurate answer. If the prompt clearly describes the user's problem or need, the model can more easily provide the expected information or solution.
d. Generate diversity: Although the prompt provides guidance for the model, it does not limit the model's creativity and the diversity of its output. Appropriate prompts can inspire the model to generate novel or non-obvious solutions while maintaining accuracy.
e. Task Orientation: In some application scenarios, prompts can specify the tasks that the model needs to perform or the types of generation, such as answering questions, providing suggestions, describing scenarios, etc. This guidance helps ensure that the model output is consistent with the needs of a specific task or application.
f. Language style and format: Through prompts, users can set the expected language style, answer structure or specific information format. This is critical to ensuring the overall quality of model output and user experience.
In summary, prompts act as a bridge and guide for interaction between users and models in large language models, and play a key role in influencing the accuracy, relevance, and diversity of model outputs. Effectively constructing and using prompts can significantly improve the practicality and responsiveness of the model.
When dealing with prompts in large language models, there are several principles that are usually considered and followed:
a. Clear and concise instructions: The prompt should clearly express the user's needs or questions and avoid vague or ambiguous descriptions to ensure that the model can understand and provide relevant and accurate answers.
b. Contextual Guidance: If the question or requirement involves a specific background or context, the prompt should contain necessary information to help the model understand, such as relevant keywords or related information.
c. Specific instructions: The prompt should contain specific instructions or questions so that the model knows the type and format of output expected by the user. For example, when asking about tourist attractions in a city, you can clearly specify that you need the name of the attraction, activity suggestions, or transportation information.
d. Avoid over-direction: While providing some context and guidance is helpful, avoid over-guidance or providing too much detail that limits the model’s creativity and the diversity of its responses.
e. The language is concise and clear: Write prompts using clear, concise, and natural language so that the model can easily understand and process them.
f. Testing and Adjustment: In real applications, it is important to test and tune the prompt to ensure that the model works as expected and can handle a variety of inputs effectively.
These principles help ensure that large language models can be efficient, accurate, and creative in their interactions with users.
In short: prompt is a starting point, which provides a hint, guidance and regulation for the big model.
a. Separator
eg: given a paragraph and asked GPT to summarize it, in this example we use ``` as a separator.
- from tool import get_completion
- text = """您应该提供尽可能清晰、具体的指示,以表达您希望模型执行的任务。这将引导模型朝向所
- 需的输出,并降低收到无关或不正确响应的可能性。不要将写清晰的提示词与写简短的提示词混淆。在
- 许多情况下,更长的提示词可以为模型提供更多的清晰度和上下文信息,从而导致更详细和相关的输出。
- """ # 需要总结的文本内容
- prompt = f"""把用三个反引号括起来的文本总结成一句话。```
本文主要介绍大模型的prompt,并且给出实战教程。即使零基础也可以实现大模型的搭建。
内容:初级阶段的修炼心法,帮助凝聚和提升内力,为后续修炼打下基础。
1、prompt
1.1含义和作用
prompt就是提示工程的意思。在大型语言模型中,"prompt"(提示)指的是用户提供给模型的输入文本或指令,用来指导模型生成相应的输出。Prompt在与模型交互时起着至关重要的作用,它影响着模型的理解、回答的准确性和内容的创造性。以下是prompt在大模型中的主要含义和作用:
a. 指导模型生成:Prompt提供了模型生成回复或输出所需的初始信息和方向。它可以包含问题、指令、关键词或上下文信息,帮助模型理解用户的意图和需要,并基于此进行相应的生成。
b. 上下文理解:通过prompt,模型能够了解当前对话或任务的上下文。这对于确保模型生成与用户期望相关和连贯的回复至关重要,特别是在长期交互或多轮对话中。
c.回答准确性:一个清晰和详细的prompt通常会导致更准确的回答。如果prompt描述清楚用户的问题或需求,模型就能更容易地提供符合预期的信息或解决方案。
d.生成多样性:尽管prompt为模型提供了指导,但它并不限制模型的创造性和输出的多样性。合适的prompt可以在保持准确性的同时,激发模型产生新颖或非显而易见的解答。
e. 任务定向:在一些应用场景中,prompt可以具体指定模型需要执行的任务或生成的类型,如回答问题、提供建议、描述情景等。这种指导有助于确保模型输出与特定任务或应用的需求相符。
f. 语言风格和格式:通过prompt,用户可以设定期望的语言风格、回答的结构或特定的信息格式。这对于确保模型输出的整体质量和用户体验至关重要。
总之,prompt在大型语言模型中充当了用户与模型之间交互的桥梁和指南,对于影响模型输出的准确性、相关性和多样性起着关键作用。有效地构建和使用prompt可以显著提高模型的实用性和响应能力。
1.2原则
在处理大型语言模型中的prompt时,有几个原则是通常被考虑和遵循的:
a.清晰和简洁的指导:prompt应该明确表达用户的需求或者问题,避免模糊或多义的描述,以确保模型能够理解并提供相关和准确的回答。
b. 上下文的引导:如果问题或需求涉及到特定的背景或上下文,prompt应该包含必要的信息来帮助模型理解,比如相关的关键词或相关信息。
c. 具体的指令:prompt中应包含具体的指令或问题,以便模型知道用户期望的输出类型和格式。例如,询问一个城市的旅游景点时,可以明确指定需要景点名称、活动建议或交通信息等。
d.避免过度指导:虽然提供一些上下文和指导是有益的,但避免过度指导或提供过多细节,以免限制模型的创造性和回答的多样性。
e. 语言简洁明了:使用清晰、简洁和自然的语言编写prompt,以便模型能够轻松理解和处理。
f.测试和调整:在实际应用中,对prompt进行测试和调整是很重要的,以确保模型能够按预期工作,并且能够有效地处理各种输入。
这些原则有助于确保大型语言模型能够在与用户的交互中表现出高效、准确和有创意的特性。
总之:prompt就是一个起点,给大模型一个提示、引导和规范的作用。
1.3使用技巧
a.分隔符
eg:给出一段话并要求 GPT 进行总结,在该示例中我们使用 ``` 来作为分隔符。
- from tool import get_completion
- text = """您应该提供尽可能清晰、具体的指示,以表达您希望模型执行的任务。这将引导模型朝向所
- 需的输出,并降低收到无关或不正确响应的可能性。不要将写清晰的提示词与写简短的提示词混淆。在
- 许多情况下,更长的提示词可以为模型提供更多的清晰度和上下文信息,从而导致更详细和相关的输出。
- """ # 需要总结的文本内容
- prompt = f"""把用三个反引号括起来的文本总结成一句话。```{text}```""" # 指令内容,使用 ``` 来分隔指令和待总结的内容
- response = get_completion(prompt)
- print(response)
- # 为了获得所需的输出,您应该提供清晰、具体的指示,避免与简短的提示词混淆,并使用更长的提示
- 词来提供更多的清晰度和上下文信息。
b.结构化输出
eg:生成三本书的标题、作者和类别,并以 JSON 的格式返回,为便于解析,我们指定了 Json 的键: book_id、title、author、genre。
- prompt = f"""请生成包括书名、作者和类别的虚构的、非真实存在的中文书籍清单,并以 JSON 格式
- 提供,其中包含以下键:book_id、title、author、genre。"""
- response = get_completion(prompt)
- print(response)
- [
- { "book_id": 1, "title": "幻境之夜", "author": "李梦飞", "genre": "奇幻小说"
- },
- ... ]
c.参考示例
Zero-Shot提示:模型只根据任务的描述生成响应,不需要任何示例。
One-Shot提示:只提供一个例子。
Few-Shot提示:提供几个例子。在提示中的作用是通过少量样本引导模型对特定任务进行学习和执行,例如通过提供少量风格或主题示例,引导模型产出具有相似风格或主题的创作。
d.让模型充当角色
示例:请以莎士比亚戏剧中的哈姆雷特的身份解释“生存还是毁灭,这是一个问题”。这个示例要求模型以莎士比亚戏剧《哈姆雷特》中主人公的角色来解释著名的“生存还是毁灭”的问题,以展示模型在不同角色中的表现能力和语境理解能力。
2、模型实战
项目任务(三大业务场景):
1.文本分类
2.文本信息抽取
3.文本匹配
大模型选择:ChatGLM-6B
采用方法:基于Few-Shot+Zero-Shot以及Instrunction的思想,设计prompt, 进而应用ChatGLM-6B模型完成相应的任务
2.1 准备工作
a.我们运用python环境来执行大模型,所以首先需要下载python,(建议用anaconda)
b.下载ChatGLM-6B模型模型,链接如下:
https://github.com/THUDM/ChatGLM-6B?tab=readme-ov-file
README中介绍了ChatGLM-6B模型和硬件需求。
量化等级 最低 GPU 显存(推理) 最低 GPU 显存(高效参数微调) FP16(无量化) 13 GB 14 GB INT8 8 GB 9 GB INT4 6 GB 7 GB
c.在你的anaconda中安装需要的依赖。在前面github中下载的包中,它其实把所有需要的依赖都放在了requirements.txt中,直接输入:
pip install -r requirements.txt
如果下载速度很慢,加上清华镜像
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
其中 transformers
库版本推荐为 4.27.1
,但理论上不低于 4.23.1
即可。
此外,如果需要在 cpu 上运行量化后的模型,还需要安装 gcc
与 openmp
。多数 Linux 发行版默认已安装。Windows 测试环境 gcc
版本为 TDM-GCC 10.3.0
, Linux 为 gcc 11.3.0
。
d.从本地加载模型:
以上代码会由 transformers
自动下载模型实现和参数。完整的模型实现可以在 Hugging Face Hub。如果你的网络环境较差,下载模型参数可能会花费较长时间甚至失败。此时可以先将模型下载到本地,然后从本地加载。
从 Hugging Face Hub 下载模型需要先安装Git LFS,然后运行
git clone https://huggingface.co/THUDM/chatglm-6b
如果你从 Hugging Face Hub 上下载 checkpoint 的速度较慢,可以只下载模型实现
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b
然后从这里手动下载模型参数文件,并将下载的文件替换到本地的 chatglm-6b
目录下。
将模型下载到本地之后,将以上代码中的 THUDM/chatglm-6b
替换为你本地的 chatglm-6b
文件夹的路径,即可从本地加载模型。
MAC注意
Mac直接加载量化后的模型出现提示 `clang: error: unsupported option '-fopenmp'
这是由于Mac由于本身缺乏omp导致的,此时可运行但是单核。需要单独安装 openmp 依赖,即可在Mac下使用OMP:
- # 参考`https://mac.r-project.org/openmp/`
- ## 假设: gcc(clang)是14.x版本,其他版本见R-Project提供的表格
- curl -O https://mac.r-project.org/openmp/openmp-14.0.6-darwin20-Release.tar.gz
- sudo tar fvxz openmp-14.0.6-darwin20-Release.tar.gz -C /
此时会安装下面几个文件:/usr/local/lib/libomp.dylib
, /usr/local/include/ompt.h
, /usr/local/include/omp.h
, /usr/local/include/omp-tools.h
。
注意:如果你之前运行ChatGLM
项目失败过,最好清一下Huggingface的缓存,i.e. 默认下是 rm -rf ${HOME}/.cache/huggingface/modules/transformers_modules/chatglm-6b-int4
。由于使用了rm
命令,请明确知道自己在删除什么。
这是官方给的解决方案,我没成功。我是在代码上加入如下:
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
防止了mac执行报错。
2.2 文本分类
我们的目的是期望模型能够帮助我们识别出这4段话中,每一句话描述的是一个什么类型的报告。
- sentences = [
- "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
对于大模型来讲,prompt 的设计非常重要,一个 明确 的 prompt 能够帮助我们更好从大模型中获得我们想要的结果。
在该任务的 prompt 设计中,我们主要考虑 2 点:
1、需要向模型解释什么叫作「文本分类任务」
2、需要让模型按照我们指定的格式输出
2.2.1导入包
- """
- 利用 LLM 进行文本分类任务。
- """
- from rich import print
- from rich.console import Console
- from transformers import AutoTokenizer, AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
2.2.2 定义init_prompts函数
- # 提供所有类别以及每个类别下的样例
- class_examples ={
- '新闻报道':'今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。',
- '财务报告':'本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。',
- '公司公告':'本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力',
- '分析师报告':'最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势'}
-
- # 定义init_prompts函数
- definit_prompts():
- '''
- 这里是对函数的功能进行注释,方便他人理解:该函数的目的是初始化前置prompt,便于模型做Few-shot
- :return: dict字典
- '''
- class_list =list(class_examples.keys())
- print(f'分类的类别数:{class_list}')
-
- pre_history =[
- (f'现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:{class_list}类别中。',
- f'好的。')
- ]
- # 遍历给的示例样本
- for _type, example in class_examples.items():
- # print(f'键--》{_type}')
- # print(f'值--》{example}')
- pre_history.append((f'"{example}"是{class_list}里的什么类别', _type))
-
- # print(f'pre_history--》{pre_history}')
- return{"class_list":class_list,"pre_history":pre_history}
a.提供一个Few-shot的样例,标注每个类别对应的话
b.将类别存储到class_list中
c.在样本提供之前给予一个prompt。即告诉模型。你是个文本分类器,要具体做什么?并给予一个答案(以逗号分隔)。(相当于一个有监督的训练)
d.遍历给的示例样本,添加到pre_history
e.返回一个字典。
打印的结果如下:
- 分类的类别数:['新闻报道','财务报告','公司公告','分析师报告']
- 键--》新闻报道
- 值--》今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。
- 键--》财务报告
- 值--》本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。
- 键--》公司公告
- 值--》本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力
- 键--》分析师报告
- 值--》最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势
- pre_history--》[("现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:['新闻报道', '财务报告', '公司公告', '分析师报告']类别中。",'好的。'),('"今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','新闻报道'),('"本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','财务报告'),('"本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','公司公告'),('"最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','分析师报告')]
2.2.3 定义inference函数
- sentences = [
- "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
- "最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会",
- ]
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待推理的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- #没啥含义,就是改变打印的颜色。
- with console.status("[bold bright_green] Model Inference..."):
- #
- sentence_prompt =f'"{sentence}"是{custom_settings["class_list"]}里的什么类别?'
- response, history = model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
- print(f'>>>[bold bright_red]sentence:{sentence}')
- print(f'>>>[bold bright_green]inference answer:{response}')
- print(f'history-->{history}')
- print("*"*80)
输入:
1、sentences :待推理的句子。
2、custom_settings :init_prompts准备好的 提示工程。
流程:
1、遍历需要推理的句子
2、执行核心代码model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
其中:
tokenizer:就是代码的分词器(可以理解为单词的最小单元)
sentence_prompt:将问题句子补充成完成的prompt
history:之前准备好的历史语句
打印的结果:
- >>>sentence:今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。
- >>>inference answer:新闻报道
- >>>sentence:ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩
- 固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。
- >>>inference answer:公司公告
- ********************************************************************************
- >>>sentence:公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。
- >>>inference answer:财务报告
- ********************************************************************************
- >>>sentence:最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会
- >>>inference answer:分析师报告
可以看到分类成功了,此时我有大胆的想法。如果我输入一句和所有类别毫不相关的话会怎么样?
sentences = ["我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地"]
它会打印成:新闻报道
这时候只要在prompt增加:
- "现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:['新闻
- 报道', '财务报告', '公司公告', '分析师报告']类别中。如果都不是就输出:'其他' ",
结果就可以变成:
- >>>sentence:我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地
- >>>inference answer:其他
2.2.4 完整代码
- # —*-coding:utf-8-*-
- """
- 利用 LLM 进行文本分类任务。
- """
- from rich importprint
- from rich.console importConsole
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
-
- # 提供所有类别以及每个类别下的样例
- class_examples ={
- '新闻报道':'今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。',
- '财务报告':'本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。',
- '公司公告':'本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力',
- '分析师报告':'最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势'}
-
- # 定义init_prompts函数
- definit_prompts():
- '''
- 这里是对函数的功能进行注释,方便他人理解:该函数的目的是初始化前置prompt,便于模型做Few-shot
- :return: dict字典
- '''
- class_list =list(class_examples.keys())
- print(f'分类的类别数:{class_list}')
-
- pre_history =[
- (f'现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:{class_list}类别中。',
- f'好的。')
- ]
- # 遍历给的示例样本
- for _type, example in class_examples.items():
- # print(f'键--》{_type}')
- # print(f'值--》{example}')
- pre_history.append((f'"{example}"是{class_list}里的什么类别', _type))
-
- # print(f'pre_history--》{pre_history}')
- return{"class_list":class_list,"pre_history":pre_history}
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待推理的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- with console.status("[bold bright_green] Model Inference..."):
- sentence_prompt =f'"{sentence}"是{custom_settings["class_list"]}里的什么类别?'
- response, history = model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
- print(f'>>>[bold bright_red]sentence:{sentence}')
- print(f'>>>[bold bright_green]inference answer:{response}')
- print(f'history-->{history}')
- print("*"*80)
-
-
- if __name__ =='__main__':
- console =Console()
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",trust_remote_code=True)
- # model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",trust_remote_code=True).float()
- model.to(device)
-
- # sentences = [
- # "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- # "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- # "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
- # "最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会",
- # ]
- # sentences = ["金融系统是建设金融强国责无旁贷的主力军,必须切实把思想和行动统一到党中央决策部署上来,深刻把握建设金融强国的精髓要义和实践要求,不断增强使命感、责任感,推动宏伟蓝图一步步变成美好现实"]
- sentences =["我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地"]
- custom_settings = init_prompts()
- print(custom_settings)
-
- inference(
- sentences,
- custom_settings
- )
主函数主要调用本次使用的tokenizer和model。
注意:
如果用mac在执行过程中选用了chatglm-6b-int4模型,会报错,
- logger.warning("Failed to load cpm_kernels:", exception)
- Message: 'Failed to load cpm_kernels:'
- Arguments: (RuntimeError('Unknown platform: darwin'),)
还能执行的话就不用管他,实在不行就切换成chatglm-6b模型即可。
如果你要用gpu跑模型,可以用这个代码替换
# model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
2.3 文本信息抽取
其实文本信息抽取也是一致的主要还是实现init_prompts函数和inference函数
2.3.1 实现init_prompts函数
- import re
- import json
-
-
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
- # 定义不同实体下的具备属性
- schema ={
- '金融':['日期','股票名称','开盘价','收盘价','成交量'],
- }
-
- # 信息抽取的模版
- IE_PATTERN ="{}nn提取上述句子中{}的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表示,多个值之间用','分隔。"
-
-
- # 提供一些例子供模型参考
- ie_examples ={
- '金融':[
- {
- 'content':'2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。',
- 'answers':{
- '日期':['2023-01-10'],
- '股票名称':['古哥-D[EOOE]美股'],
- '开盘价':['100美元'],
- '收盘价':['102美元'],
- '成交量':['520000'],
- }
- }
- ]
- }
-
-
- # 定义init_prompts函数
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- ie_pre_history =[
- (
- "现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未提及']来表示,多个值之间用','分隔。",
- '好的,请输入您的句子。'
- )
- ]
- for _type, example_list in ie_examples.items():
- print(f'_type-->{_type}')
- print(f'example_list-->{example_list}')
- print(f'*'*80)
- for example in example_list:
- sentence = example["content"]
- properties_str =', '.join(schema[_type])
- print(f'properties_str-->{properties_str}')
- schema_str_list =f'"{_type}"({properties_str})'
- print(f'schema_str_list-->{schema_str_list}')
-
- sentence_with_prompt = IE_PATTERN.format(sentence, schema_str_list)
- print(f'sentence_with_prompt-->{sentence_with_prompt}')
- ie_pre_history.append((f"{sentence_with_prompt}",f"{json.dumps(example['answers'], ensure_ascii=False)}"))
- print(f'ie_pre_history-->{ie_pre_history}')
-
- return{"ie_pre_history":ie_pre_history}
-
- init_prompts()
a.提供一个Few-shot的样例,定义不同实体下的具备属性
b.将prompt补充完整
c.增加至ie_pre_history当中
打印如下:
- _type-->金融
- example_list-->[{'content':
- '2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元
- ,随后回落至98美元,最终以102美元收盘,成交量达到520000。','answers':{'日期':
- ['2023-01-10'],'股票名称':['古哥-D[EOOE]美股'],'开盘价':['100美元'],
- '收盘价':['102美元'],'成交量':['520000']}}]
- ********************************************************************************
- properties_str-->日期,股票名称,开盘价,收盘价,成交量
- schema_str_list-->"金融"(日期,股票名称,开盘价,收盘价,成交量)
- sentence_with_prompt-->2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美
- 元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。
-
- 提取上述句子中"金融"(日期,股票名称,开盘价,收盘价,
- 成交量)的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表
- 示,多个值之间用','分隔。
- ie_pre_history-->[("现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要
- 帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未
- 提及']来表示,多个值之间用','分隔。",'好的,请输入您的句子。'),
- ('2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元
- ,随后回落至98美元,最终以102美元收盘,成交量达到520000。nn提取上述句子中"金融
- "(日期, 股票名称, 开盘价, 收盘价,
- 成交量)的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来
- 表示,多个值之间用','分隔。','{"日期": ["2023-01-10"], "股票名称":
- ["古哥-D[EOOE]美股"], "开盘价": ["100美元"], "收盘价": ["102美元"], "成交量":
- ["520000"]}')]
2.3.2 定义inference函数
- def inference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待抽取的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- cls_res ="金融"
- if cls_res notin schema:
- print(f'The type model inferenced {cls_res} which is not in schema dict, exited.')
- exit()
- properties_str =', '.join(schema[cls_res])
- schema_str_list =f'"{cls_res}"({properties_str})'
- sentence_with_ie_prompt = IE_PATTERN.format(sentence, schema_str_list)
- # print(f'sentence_with_prompt-->{sentence_with_ie_prompt}')
- ie_res, history = model.chat(tokenizer,
- sentence_with_ie_prompt,
- history=custom_settings["ie_pre_history"])
- ie_res = clean_response(ie_res)
- print(f'>>> [bold bright_red]sentence: {sentence}')
- print(f'>>> [bold bright_green]inference answer:{ie_res} ')
a.定义输入:
sentences (List[str]): 待抽取的句子。custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
b.定义类别:cls_res = "金融"
这里将类别写死了。如果有多个类别。可以先利用 文本分类 实现后,在进行文本信息抽取。
c.将输入的sentences补充完整,调用 model.chat
d.将模型结果做一个后处理,提取json模型并输出
打印如下:
- >>> sentence:
- 2023-02-15,寓意吉祥的节日,股票佰笃[BD]美股开盘价10美元,虽然经历了波动,但最终
- 以13美元收盘,成交量微幅增加至460,000,投资者情绪较为平稳。
- >>> inference answer:{'日期': ['2023-02-15'], '股票名称': ['佰笃[BD]美股'],
- '开盘价': ['10美元'], '收盘价': ['13美元'], '成交量': ['460,000']}
2.3.3 完整代码
- import re
- import json
-
-
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
- # 定义不同实体下的具备属性
- schema ={
- '金融':['日期','股票名称','开盘价','收盘价','成交量'],
- }
-
- # 信息抽取的模版
- IE_PATTERN ="{}nn提取上述句子中{}的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表示,多个值之间用','分隔。"
-
-
- # 提供一些例子供模型参考
- ie_examples ={
- '金融':[
- {
- 'content':'2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。',
- 'answers':{
- '日期':['2023-01-10'],
- '股票名称':['古哥-D[EOOE]美股'],
- '开盘价':['100美元'],
- '收盘价':['102美元'],
- '成交量':['520000'],
- }
- }
- ]
- }
-
- # 定义init_prompts函数
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- ie_pre_history =[
- (
- "现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未提及']来表示,多个值之间用','分隔。",
- '好的,请输入您的句子。'
- )
- ]
- for _type, example_list in ie_examples.items():
- # print(f'_type-->{_type}')
- # print(f'example_list-->{example_list}')
- # print(f'*'*80)
- for example in example_list:
- sentence = example["content"]
- properties_str =', '.join(schema[_type])
- # print(f'properties_str-->{properties_str}')
- schema_str_list =f'"{_type}"({properties_str})'
- # print(f'schema_str_list-->{schema_str_list}')
-
- sentence_with_prompt = IE_PATTERN.format(sentence, schema_str_list)
- print(f'sentence_with_prompt-->{sentence_with_prompt}')
- ie_pre_history.append((f"{sentence_with_prompt}",f"{json.dumps(example['answers'], ensure_ascii=False)}"))
- print(f'ie_pre_history-->{ie_pre_history}')
-
- return{"ie_pre_history":ie_pre_history}
-
- defclean_response(response: str):
- """
- 后处理模型输出。
- Args:
- response (str): _description_
- """
- if'```json'in response:
- res = re.findall(r'```json(.*?)```', response)
- iflen(res)and res[0]:
- response = res[0]
- response = response.replace('、',',')
- try:
- return json.loads(response)
- except:
- return response
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待抽取的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- cls_res ="金融"
- if cls_res notin schema:
- print(f'The type model inferenced {cls_res} which is not in schema dict, exited.')
- exit()
- properties_str =', '.join(schema[cls_res])
- schema_str_list =f'"{cls_res}"({properties_str})'
- sentence_with_ie_prompt = IE_PATTERN.format(sentence, schema_str_list)
- # print(f'sentence_with_prompt-->{sentence_with_ie_prompt}')
- ie_res, history = model.chat(tokenizer,
- sentence_with_ie_prompt,
- history=custom_settings["ie_pre_history"])
- ie_res = clean_response(ie_res)
- print(f'>>> [bold bright_red]sentence: {sentence}')
- print(f'>>> [bold bright_green]inference answer:{ie_res} ')
-
-
-
- if __name__ =='__main__':
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True)
- #model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b",
- # trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True).float()
- model.to(device)
-
- sentences =[
- '2023-02-15,寓意吉祥的节日,股票佰笃[BD]美股开盘价10美元,虽然经历了波动,但最终以13美元收盘,成交量微幅增加至460,000,投资者情绪较为平稳。',
- '2023-04-05,市场迎来轻松氛围,股票盘古(0021)开盘价23元,尽管经历了波动,但最终以26美元收盘,成交量缩小至310,000,投资者保持观望态度。',
- ]
-
- custom_settings = init_prompts()
-
- inference(
- sentences,
- custom_settings
- )
2.4 文本匹配
文本匹配具体和我之前做的bert是一个项目。这里主要食用prompt实现。和上面基本一致,就不重点阐述了
完整代码如下:
2.4.1 完整代码
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
-
- import os
-
-
- # 提供相似,不相似的语义匹配例子
- examples ={
- '是':[
- ('公司ABC发布了季度财报,显示盈利增长。','财报披露,公司ABC利润上升。'),
- ],
- '不是':[
- ('黄金价格下跌,投资者抛售。','外汇市场交易额创下新高。'),
- ('央行降息,刺激经济增长。','新能源技术的创新。')
- ]
- }
-
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- pre_history =[
- (
- '现在你需要帮助我完成文本匹配任务,当我给你两个句子时,你需要回答我这两句话语义是否相似。只需要回答是否相似,不要做多余的回答。',
- '好的,我将只回答”是“或”不是“。'
- )
- ]
- for key, sentence_pairs in examples.items():
- # print(f'key-->{key}')
- # print(f'sentence_pairs-->{sentence_pairs}')
- for sentence_pair in sentence_pairs:
- sentence1, sentence2 = sentence_pair
- # print(f'sentence1-->{sentence1}')
- # print(f'sentence2-->{sentence2}')
- pre_history.append((f'句子一:{sentence1}n句子二:{sentence2}n上面两句话是相似的语义吗?',
- key))
- return{"pre_history": pre_history}
-
- definference(
- sentence_pairs: list,
- custom_settings: dict
- ):
- """
- 推理函数。
- Args:
- model (transformers.AutoModel): Language Model 模型。
- sentence_pairs (List[str]): 待推理的句子对。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence_pair in sentence_pairs:
- sentence1, sentence2 = sentence_pair
- sentence_with_prompt =f'句子一: {sentence1}n句子二: {sentence2}n上面两句话是相似的语义吗?'
- response, history = model.chat(tokenizer, sentence_with_prompt, history=custom_settings['pre_history'])
- print(f'>>> [bold bright_red]sentence: {sentence_pair}')
- print(f'>>> [bold bright_green]inference answer: {response}')
- # print(history)
-
- if __name__ =='__main__':
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("/Users/ligang/PycharmProjects/llm/ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True)
- #model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b",
- # trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("/Users/ligang/PycharmProjects/llm/ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True).float()
- model.to(device)
-
- sentence_pairs =[
- ('股票市场今日大涨,投资者乐观。','持续上涨的市场让投资者感到满意。'),
- ('油价大幅下跌,能源公司面临挑战。','未来智能城市的建设趋势愈发明显。'),
- ('利率上升,影响房地产市场。','高利率对房地产有一定冲击。'),
- ]
-
- custom_settings = init_prompts()
- inference(
- sentence_pairs,
- custom_settings
- )
```""" # 指令内容,使用 ``` 来分隔指令和待总结的内容 - response = get_completion(prompt)
- print(response)
- # 为了获得所需的输出,您应该提供清晰、具体的指示,避免与简短的提示词混淆,并使用更长的提示
- 词来提供更多的清晰度和上下文信息。
b. Structured output
Eg: Generate the titles, authors and categories of three books and return them in JSON format. For ease of parsing, we specify the Json keys: book_id, title, author, genre.
- prompt = f"""请生成包括书名、作者和类别的虚构的、非真实存在的中文书籍清单,并以 JSON 格式
- 提供,其中包含以下键:book_id、title、author、genre。"""
- response = get_completion(prompt)
- print(response)
- [
- { "book_id": 1, "title": "幻境之夜", "author": "李梦飞", "genre": "奇幻小说"
- },
- ... ]
c. Reference examples
Zero-Shot Tips:The model generates responses based solely on the description of the task, without requiring any examples.
One-Shot Tips:Just one example is provided.
Few-Shot Tips:Provide a few examples. The role of prompts is to guide the model to learn and perform a specific task through a small number of samples, such as by providing a small number of style or theme examples, guiding the model to produce creations with similar style or theme.
d. Let the model play a role
Example: Explain "To be or not to be, that is the question" as Hamlet from Shakespeare's play. This example asks the model to explain the famous "to be or not to be" question as the protagonist of Shakespeare's play Hamlet, to demonstrate the model's performance in different roles and contextual understanding.
Project Mission(Three major business scenarios):
1. Text Classification
2. Text information extraction
3. Text Matching
Large model selection:ChatGLM-6B
adapting methods:Based on the ideas of Few-Shot+Zero-Shot and Instrunction, we designed prompts and then applied the ChatGLM-6B model to complete the corresponding tasks
a. We use the Python environment to execute large models, so we first need to download Python (anaconda is recommended)
b. Download the ChatGLM-6B model from the following link:
https://github.com/THUDM/ChatGLM-6B?tab=readme-ov-file
The ChatGLM-6B model and hardware requirements are introduced in the README.
Quantization level | Minimum GPU memory(reasoning) | Minimum GPU memory(Efficient parameter fine-tuning) |
FP16 (no quantization) | 13 GB | 14 GB |
INT8 | 8 GB | 9 GB |
INT4 | 6 GB | 7 GB |
c. Install the required dependencies in your anaconda. In the package downloaded from github above, it actually puts all the required dependencies in requirements.txt. Just enter:
pip install -r requirements.txt
If the download speed is very slow, add Tsinghua mirror
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
intransformers
The recommended library version is4.27.1
, but theoretically not less than4.23.1
That's it.
In addition, if you need to run the quantized model on the CPU, you also need to installgcc
andopenmp
Most Linux distributions have it installed by default. Windows test environmentgcc
VersionTDM-GCC 10.3.0
, Linux isgcc 11.3.0
。
d. Load the model from local:
The above code will betransformers
Automatically download the model implementation and parameters. The complete model implementation can be found on Hugging Face Hub. If your network environment is poor, downloading the model parameters may take a long time or even fail. In this case, you can first download the model to your local computer and then load it from there.
To download the model from Hugging Face Hub, you need to install Git LFS first, then run
git clone https://huggingface.co/THUDM/chatglm-6b
If you are slow to download checkpoints from Hugging Face Hub, you can download only the model implementation
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b
Then manually download the model parameter file from here and replace the downloaded file with the localchatglm-6b
Under contents.
After downloading the model locally, replaceTHUDM/chatglm-6b
Replace with your localchatglm-6b
The path to the folder can be used to load the model locally.
MAC Note
When Mac directly loads the quantized model, a prompt appears: `clang: error: unsupported option '-fopenmp'
This is because Mac lacks omp. It can run but only on a single core. You need to install openmp dependencies separately to use OMP on Mac:
- # 参考`https://mac.r-project.org/openmp/`
- ## 假设: gcc(clang)是14.x版本,其他版本见R-Project提供的表格
- curl -O https://mac.r-project.org/openmp/openmp-14.0.6-darwin20-Release.tar.gz
- sudo tar fvxz openmp-14.0.6-darwin20-Release.tar.gz -C /
The following files will be installed at this time:/usr/local/lib/libomp.dylib
, /usr/local/include/ompt.h
, /usr/local/include/omp.h
, /usr/local/include/omp-tools.h
。
Note: If you previously ran
ChatGLM
If the project fails, it is best to clear the Huggingface cache. By default, IErm -rf ${HOME}/.cache/huggingface/modules/transformers_modules/chatglm-6b-int4
. Due to the use ofrm
command, please know clearly what you are deleting.
This is the official solution, but I didn't succeed. I added the following to the code:
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
Prevents mac from reporting errors.
Our goal is to expect the model to help us identify what type of report each sentence in these four paragraphs describes.
- sentences = [
- "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
For large models, prompt design is very important. A clear prompt can help us better obtain the results we want from large models.
In the prompt design of this task, we mainly consider two points:
1. You need to explain to the model what a “text classification task” is
2. The model needs to be output in the format we specify
- """
- 利用 LLM 进行文本分类任务。
- """
- from rich import print
- from rich.console import Console
- from transformers import AutoTokenizer, AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
- # 提供所有类别以及每个类别下的样例
- class_examples ={
- '新闻报道':'今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。',
- '财务报告':'本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。',
- '公司公告':'本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力',
- '分析师报告':'最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势'}
-
- # 定义init_prompts函数
- definit_prompts():
- '''
- 这里是对函数的功能进行注释,方便他人理解:该函数的目的是初始化前置prompt,便于模型做Few-shot
- :return: dict字典
- '''
- class_list =list(class_examples.keys())
- print(f'分类的类别数:{class_list}')
-
- pre_history =[
- (f'现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:{class_list}类别中。',
- f'好的。')
- ]
- # 遍历给的示例样本
- for _type, example in class_examples.items():
- # print(f'键--》{_type}')
- # print(f'值--》{example}')
- pre_history.append((f'"{example}"是{class_list}里的什么类别', _type))
-
- # print(f'pre_history--》{pre_history}')
- return{"class_list":class_list,"pre_history":pre_history}
a. Provide a few-shot example and label the words corresponding to each category
b. Store the categories in class_list
c. Give a prompt before providing the sample. That is, tell the model. You are a text classifier, what do you want to do specifically? And give an answer (separated by commas). (Equivalent to a supervised training)
d. Traverse the given sample and add it to pre_history
e. Returns a dictionary.
The printed results are as follows:
- 分类的类别数:['新闻报道','财务报告','公司公告','分析师报告']
- 键--》新闻报道
- 值--》今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。
- 键--》财务报告
- 值--》本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。
- 键--》公司公告
- 值--》本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力
- 键--》分析师报告
- 值--》最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势
- pre_history--》[("现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:['新闻报道', '财务报告', '公司公告', '分析师报告']类别中。",'好的。'),('"今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','新闻报道'),('"本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','财务报告'),('"本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','公司公告'),('"最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势"是['新闻报道', '财务报告', '公司公告', '分析师报告']里的什么类别','分析师报告')]
- sentences = [
- "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
- "最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会",
- ]
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待推理的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- #没啥含义,就是改变打印的颜色。
- with console.status("[bold bright_green] Model Inference..."):
- #
- sentence_prompt =f'"{sentence}"是{custom_settings["class_list"]}里的什么类别?'
- response, history = model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
- print(f'>>>[bold bright_red]sentence:{sentence}')
- print(f'>>>[bold bright_green]inference answer:{response}')
- print(f'history-->{history}')
- print("*"*80)
enter:
1. Sentences: sentences to be inferred.
2. custom_settings: prompts project prepared by init_prompts.
process:
1. Traverse the sentences that need reasoning
2. Execute the core code model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
in:
Tokenizer: It is the word segmenter of the code (which can be understood as the smallest unit of a word)
sentence_prompt: Complete the question sentence into a prompt
history: previously prepared historical statements
Printed results:
- >>>sentence:今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。
- >>>inference answer:新闻报道
- >>>sentence:ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩
- 固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。
- >>>inference answer:公司公告
- ********************************************************************************
- >>>sentence:公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。
- >>>inference answer:财务报告
- ********************************************************************************
- >>>sentence:最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会
- >>>inference answer:分析师报告
You can see that the classification is successful. At this point I have a bold idea. What if I enter a sentence that is completely unrelated to all categories?
sentences = ["我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地"]
It will print: News Report
At this time, just add in the prompt:
- "现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:['新闻
- 报道', '财务报告', '公司公告', '分析师报告']类别中。如果都不是就输出:'其他' ",
The result can be turned into:
- >>>sentence:我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地
- >>>inference answer:其他
- # —*-coding:utf-8-*-
- """
- 利用 LLM 进行文本分类任务。
- """
- from rich importprint
- from rich.console importConsole
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
-
- # 提供所有类别以及每个类别下的样例
- class_examples ={
- '新闻报道':'今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。',
- '财务报告':'本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。',
- '公司公告':'本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力',
- '分析师报告':'最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势'}
-
- # 定义init_prompts函数
- definit_prompts():
- '''
- 这里是对函数的功能进行注释,方便他人理解:该函数的目的是初始化前置prompt,便于模型做Few-shot
- :return: dict字典
- '''
- class_list =list(class_examples.keys())
- print(f'分类的类别数:{class_list}')
-
- pre_history =[
- (f'现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:{class_list}类别中。',
- f'好的。')
- ]
- # 遍历给的示例样本
- for _type, example in class_examples.items():
- # print(f'键--》{_type}')
- # print(f'值--》{example}')
- pre_history.append((f'"{example}"是{class_list}里的什么类别', _type))
-
- # print(f'pre_history--》{pre_history}')
- return{"class_list":class_list,"pre_history":pre_history}
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待推理的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- with console.status("[bold bright_green] Model Inference..."):
- sentence_prompt =f'"{sentence}"是{custom_settings["class_list"]}里的什么类别?'
- response, history = model.chat(tokenizer, sentence_prompt, history=custom_settings['pre_history'])
- print(f'>>>[bold bright_red]sentence:{sentence}')
- print(f'>>>[bold bright_green]inference answer:{response}')
- print(f'history-->{history}')
- print("*"*80)
-
-
- if __name__ =='__main__':
- console =Console()
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",trust_remote_code=True)
- # model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",trust_remote_code=True).float()
- model.to(device)
-
- # sentences = [
- # "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- # "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- # "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
- # "最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会",
- # ]
- # sentences = ["金融系统是建设金融强国责无旁贷的主力军,必须切实把思想和行动统一到党中央决策部署上来,深刻把握建设金融强国的精髓要义和实践要求,不断增强使命感、责任感,推动宏伟蓝图一步步变成美好现实"]
- sentences =["我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地"]
- custom_settings = init_prompts()
- print(custom_settings)
-
- inference(
- sentences,
- custom_settings
- )
The main function mainly calls the tokenizer and model used this time.
Notice:
If you use a Mac and select the chatglm-6b-int4 model during execution, an error will be reported.
- logger.warning("Failed to load cpm_kernels:", exception)
- Message: 'Failed to load cpm_kernels:'
- Arguments: (RuntimeError('Unknown platform: darwin'),)
If it still works, just ignore it. If it doesn't work, just switch to the chatglm-6b model.
If you want to run the model with GPU, you can replace it with this code
# model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
In fact, text information extraction is also the same, mainly implementing the init_prompts function and the inference function
- import re
- import json
-
-
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
- # 定义不同实体下的具备属性
- schema ={
- '金融':['日期','股票名称','开盘价','收盘价','成交量'],
- }
-
- # 信息抽取的模版
- IE_PATTERN ="{}nn提取上述句子中{}的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表示,多个值之间用','分隔。"
-
-
- # 提供一些例子供模型参考
- ie_examples ={
- '金融':[
- {
- 'content':'2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。',
- 'answers':{
- '日期':['2023-01-10'],
- '股票名称':['古哥-D[EOOE]美股'],
- '开盘价':['100美元'],
- '收盘价':['102美元'],
- '成交量':['520000'],
- }
- }
- ]
- }
-
-
- # 定义init_prompts函数
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- ie_pre_history =[
- (
- "现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未提及']来表示,多个值之间用','分隔。",
- '好的,请输入您的句子。'
- )
- ]
- for _type, example_list in ie_examples.items():
- print(f'_type-->{_type}')
- print(f'example_list-->{example_list}')
- print(f'*'*80)
- for example in example_list:
- sentence = example["content"]
- properties_str =', '.join(schema[_type])
- print(f'properties_str-->{properties_str}')
- schema_str_list =f'"{_type}"({properties_str})'
- print(f'schema_str_list-->{schema_str_list}')
-
- sentence_with_prompt = IE_PATTERN.format(sentence, schema_str_list)
- print(f'sentence_with_prompt-->{sentence_with_prompt}')
- ie_pre_history.append((f"{sentence_with_prompt}",f"{json.dumps(example['answers'], ensure_ascii=False)}"))
- print(f'ie_pre_history-->{ie_pre_history}')
-
- return{"ie_pre_history":ie_pre_history}
-
- init_prompts()
a. Provide a few-shot example and define the attributes of different entities
b. Complete the prompt
c. Add to ie_pre_history
Prints as follows:
- _type-->金融
- example_list-->[{'content':
- '2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元
- ,随后回落至98美元,最终以102美元收盘,成交量达到520000。','answers':{'日期':
- ['2023-01-10'],'股票名称':['古哥-D[EOOE]美股'],'开盘价':['100美元'],
- '收盘价':['102美元'],'成交量':['520000']}}]
- ********************************************************************************
- properties_str-->日期,股票名称,开盘价,收盘价,成交量
- schema_str_list-->"金融"(日期,股票名称,开盘价,收盘价,成交量)
- sentence_with_prompt-->2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美
- 元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。
-
- 提取上述句子中"金融"(日期,股票名称,开盘价,收盘价,
- 成交量)的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表
- 示,多个值之间用','分隔。
- ie_pre_history-->[("现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要
- 帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未
- 提及']来表示,多个值之间用','分隔。",'好的,请输入您的句子。'),
- ('2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元
- ,随后回落至98美元,最终以102美元收盘,成交量达到520000。nn提取上述句子中"金融
- "(日期, 股票名称, 开盘价, 收盘价,
- 成交量)的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来
- 表示,多个值之间用','分隔。','{"日期": ["2023-01-10"], "股票名称":
- ["古哥-D[EOOE]美股"], "开盘价": ["100美元"], "收盘价": ["102美元"], "成交量":
- ["520000"]}')]
- def inference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待抽取的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- cls_res ="金融"
- if cls_res notin schema:
- print(f'The type model inferenced {cls_res} which is not in schema dict, exited.')
- exit()
- properties_str =', '.join(schema[cls_res])
- schema_str_list =f'"{cls_res}"({properties_str})'
- sentence_with_ie_prompt = IE_PATTERN.format(sentence, schema_str_list)
- # print(f'sentence_with_prompt-->{sentence_with_ie_prompt}')
- ie_res, history = model.chat(tokenizer,
- sentence_with_ie_prompt,
- history=custom_settings["ie_pre_history"])
- ie_res = clean_response(ie_res)
- print(f'>>> [bold bright_red]sentence: {sentence}')
- print(f'>>> [bold bright_green]inference answer:{ie_res} ')
a. Define input:
sentences (List[str]): sentences to be extracted. custom_settings (dict): initial settings, including artificially given few-shot examples.
b. Define category: cls_res = "Finance"
The categories are hardcoded here. If there are multiple categories, you can first use text classification to implement it, and then perform text information extraction.
c. Complete the input sentences and call model.chat
d. Post-process the model results, extract the json model and output
Prints as follows:
- >>> sentence:
- 2023-02-15,寓意吉祥的节日,股票佰笃[BD]美股开盘价10美元,虽然经历了波动,但最终
- 以13美元收盘,成交量微幅增加至460,000,投资者情绪较为平稳。
- >>> inference answer:{'日期': ['2023-02-15'], '股票名称': ['佰笃[BD]美股'],
- '开盘价': ['10美元'], '收盘价': ['13美元'], '成交量': ['460,000']}
- import re
- import json
-
-
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
-
- # 定义不同实体下的具备属性
- schema ={
- '金融':['日期','股票名称','开盘价','收盘价','成交量'],
- }
-
- # 信息抽取的模版
- IE_PATTERN ="{}nn提取上述句子中{}的实体,并按照JSON格式输出,上述句子中不存在的信息用['原文中未提及']来表示,多个值之间用','分隔。"
-
-
- # 提供一些例子供模型参考
- ie_examples ={
- '金融':[
- {
- 'content':'2023-01-10,股市震荡。股票古哥-D[EOOE]美股今日开盘价100美元,一度飙升至105美元,随后回落至98美元,最终以102美元收盘,成交量达到520000。',
- 'answers':{
- '日期':['2023-01-10'],
- '股票名称':['古哥-D[EOOE]美股'],
- '开盘价':['100美元'],
- '收盘价':['102美元'],
- '成交量':['520000'],
- }
- }
- ]
- }
-
- # 定义init_prompts函数
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- ie_pre_history =[
- (
- "现在你需要帮助我完成信息抽取任务,当我给你一个句子时,你需要帮我抽取出句子中实体信息,并按照JSON的格式输出,上述句子中没有的信息用['原文中未提及']来表示,多个值之间用','分隔。",
- '好的,请输入您的句子。'
- )
- ]
- for _type, example_list in ie_examples.items():
- # print(f'_type-->{_type}')
- # print(f'example_list-->{example_list}')
- # print(f'*'*80)
- for example in example_list:
- sentence = example["content"]
- properties_str =', '.join(schema[_type])
- # print(f'properties_str-->{properties_str}')
- schema_str_list =f'"{_type}"({properties_str})'
- # print(f'schema_str_list-->{schema_str_list}')
-
- sentence_with_prompt = IE_PATTERN.format(sentence, schema_str_list)
- print(f'sentence_with_prompt-->{sentence_with_prompt}')
- ie_pre_history.append((f"{sentence_with_prompt}",f"{json.dumps(example['answers'], ensure_ascii=False)}"))
- print(f'ie_pre_history-->{ie_pre_history}')
-
- return{"ie_pre_history":ie_pre_history}
-
- defclean_response(response: str):
- """
- 后处理模型输出。
- Args:
- response (str): _description_
- """
- if'```json'in response:
- res = re.findall(r'```json(.*?)```', response)
- iflen(res)and res[0]:
- response = res[0]
- response = response.replace('、',',')
- try:
- return json.loads(response)
- except:
- return response
-
- definference(sentences: list,
- custom_settings: dict):
- """
- 推理函数。
- Args:
- sentences (List[str]): 待抽取的句子。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence in sentences:
- cls_res ="金融"
- if cls_res notin schema:
- print(f'The type model inferenced {cls_res} which is not in schema dict, exited.')
- exit()
- properties_str =', '.join(schema[cls_res])
- schema_str_list =f'"{cls_res}"({properties_str})'
- sentence_with_ie_prompt = IE_PATTERN.format(sentence, schema_str_list)
- # print(f'sentence_with_prompt-->{sentence_with_ie_prompt}')
- ie_res, history = model.chat(tokenizer,
- sentence_with_ie_prompt,
- history=custom_settings["ie_pre_history"])
- ie_res = clean_response(ie_res)
- print(f'>>> [bold bright_red]sentence: {sentence}')
- print(f'>>> [bold bright_green]inference answer:{ie_res} ')
-
-
-
- if __name__ =='__main__':
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True)
- #model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b",
- # trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True).float()
- model.to(device)
-
- sentences =[
- '2023-02-15,寓意吉祥的节日,股票佰笃[BD]美股开盘价10美元,虽然经历了波动,但最终以13美元收盘,成交量微幅增加至460,000,投资者情绪较为平稳。',
- '2023-04-05,市场迎来轻松氛围,股票盘古(0021)开盘价23元,尽管经历了波动,但最终以26美元收盘,成交量缩小至310,000,投资者保持观望态度。',
- ]
-
- custom_settings = init_prompts()
-
- inference(
- sentences,
- custom_settings
- )
Text matching is a project similar to the one I did before, BERT. Here we mainly use prompt to implement it. It is basically the same as above, so I won’t elaborate on it.
The complete code is as follows:
- from rich importprint
- from transformers importAutoTokenizer,AutoModel
-
- import os
-
-
- # 提供相似,不相似的语义匹配例子
- examples ={
- '是':[
- ('公司ABC发布了季度财报,显示盈利增长。','财报披露,公司ABC利润上升。'),
- ],
- '不是':[
- ('黄金价格下跌,投资者抛售。','外汇市场交易额创下新高。'),
- ('央行降息,刺激经济增长。','新能源技术的创新。')
- ]
- }
-
- definit_prompts():
- """
- 初始化前置prompt,便于模型做 incontext learning。
- """
- pre_history =[
- (
- '现在你需要帮助我完成文本匹配任务,当我给你两个句子时,你需要回答我这两句话语义是否相似。只需要回答是否相似,不要做多余的回答。',
- '好的,我将只回答”是“或”不是“。'
- )
- ]
- for key, sentence_pairs in examples.items():
- # print(f'key-->{key}')
- # print(f'sentence_pairs-->{sentence_pairs}')
- for sentence_pair in sentence_pairs:
- sentence1, sentence2 = sentence_pair
- # print(f'sentence1-->{sentence1}')
- # print(f'sentence2-->{sentence2}')
- pre_history.append((f'句子一:{sentence1}n句子二:{sentence2}n上面两句话是相似的语义吗?',
- key))
- return{"pre_history": pre_history}
-
- definference(
- sentence_pairs: list,
- custom_settings: dict
- ):
- """
- 推理函数。
- Args:
- model (transformers.AutoModel): Language Model 模型。
- sentence_pairs (List[str]): 待推理的句子对。
- custom_settings (dict): 初始设定,包含人为给定的 few-shot example。
- """
- for sentence_pair in sentence_pairs:
- sentence1, sentence2 = sentence_pair
- sentence_with_prompt =f'句子一: {sentence1}n句子二: {sentence2}n上面两句话是相似的语义吗?'
- response, history = model.chat(tokenizer, sentence_with_prompt, history=custom_settings['pre_history'])
- print(f'>>> [bold bright_red]sentence: {sentence_pair}')
- print(f'>>> [bold bright_green]inference answer: {response}')
- # print(history)
-
- if __name__ =='__main__':
- #device = 'cuda:0'
- device ='cpu'
- tokenizer =AutoTokenizer.from_pretrained("/Users/ligang/PycharmProjects/llm/ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True)
- #model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b",
- # trust_remote_code=True).half().cuda()
- model =AutoModel.from_pretrained("/Users/ligang/PycharmProjects/llm/ChatGLM-6B/THUDM/chatglm-6b-int4",
- trust_remote_code=True).float()
- model.to(device)
-
- sentence_pairs =[
- ('股票市场今日大涨,投资者乐观。','持续上涨的市场让投资者感到满意。'),
- ('油价大幅下跌,能源公司面临挑战。','未来智能城市的建设趋势愈发明显。'),
- ('利率上升,影响房地产市场。','高利率对房地产有一定冲击。'),
- ]
-
- custom_settings = init_prompts()
- inference(
- sentence_pairs,
- custom_settings
- )