le mie informazioni di contatto
Posta[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Questo articolo introduce principalmente istruzioni per modelli di grandi dimensioni e fornisce esercitazioni pratiche. I modelli di grandi dimensioni possono essere costruiti anche senza fondamenta.
Contenuto: la fase iniziale dell'allenamento mentale aiuta a condensare e potenziare la forza interna e getta le basi per l'allenamento successivo.
prompt significa sollecitare il progetto. Nei modelli linguistici di grandi dimensioni, un "prompt" si riferisce al testo di input o alle istruzioni fornite dall'utente al modello per guidare il modello a generare l'output corrispondente. Il prompt gioca un ruolo fondamentale quando si interagisce con il modello, il che influisce sulla comprensione del modello, sull'accuratezza delle risposte e sulla creatività dei contenuti. Di seguito sono riportati i principali significati e funzioni del prompt nei modelli di grandi dimensioni:
UN.Generazione del modello guida : Il prompt fornisce le informazioni iniziali e la direzione necessarie al modello per generare una risposta o un output. Può contenere domande, istruzioni, parole chiave o informazioni contestuali per aiutare il modello a comprendere le intenzioni e le esigenze dell'utente e generare informazioni corrispondenti sulla base di queste.
B.comprensione contestuale : Attraverso i suggerimenti, il modello può comprendere il contesto della conversazione o dell'attività corrente. Ciò è fondamentale per garantire che il modello generi risposte pertinenti e coerenti con le aspettative degli utenti, soprattutto nelle interazioni a lungo termine o in più cicli di conversazioni.
c. Precisione della risposta : Una richiesta chiara e dettagliata di solito porta a una risposta più accurata. Se il prompt descrive chiaramente il problema o l'esigenza dell'utente, il modello può fornire più facilmente le informazioni o le soluzioni previste.
d.Generare diversità : Sebbene il prompt fornisca una guida per il modello, non limita la creatività del modello e la diversità dei risultati. Suggerimenti appropriati possono ispirare i modelli a produrre soluzioni nuove o non ovvie mantenendo l'accuratezza.
e.orientamento al compito : In alcuni scenari applicativi, il prompt può specificare le attività che il modello deve eseguire o il tipo di generazione, come rispondere a domande, fornire suggerimenti, descrivere scenari, ecc. Queste indicazioni aiutano a garantire che l'output del modello soddisfi le esigenze di un'attività o di un'applicazione specifica.
F.Stile e formato della lingua : Attraverso il prompt, gli utenti possono impostare lo stile linguistico desiderato, la struttura della risposta o il formato specifico delle informazioni. Ciò è fondamentale per garantire la qualità complessiva dell'output del modello e dell'esperienza dell'utente.
In breve, il prompt funge da ponte e guida per l’interazione tra utenti e modelli in modelli linguistici di grandi dimensioni e svolge un ruolo chiave nell’influenzare l’accuratezza, la pertinenza e la diversità dell’output del modello. La creazione e l'utilizzo efficaci dei prompt possono migliorare significativamente l'utilità e la reattività del modello.
Quando si tratta di prompt in modelli linguistici di grandi dimensioni, ci sono diversi principi che vengono solitamente considerati e seguiti:
a. Guida chiara e concisa:prompt dovrebbe esprimere chiaramente le esigenze o le domande dell'utente ed evitare descrizioni vaghe o ambigue per garantire che il modello possa comprendere e fornire risposte pertinenti e accurate.
B.guida contestuale: se la domanda o il requisito riguardano un background o un contesto specifico, il prompt dovrebbe contenere le informazioni necessarie per aiutare il modello a comprendere, come parole chiave pertinenti o informazioni correlate.
C.istruzioni specifiche :Il prompt dovrebbe contenere istruzioni o domande specifiche in modo che il modello conosca il tipo e il formato dell'output previsto dall'utente. Ad esempio, quando chiedi informazioni sulle attrazioni turistiche di una città, puoi specificare chiaramente che ti servono nomi di attrazioni, suggerimenti di attività o informazioni sui trasporti.
d. Evitare una guida eccessiva: Sebbene sia utile fornire contesto e indicazioni, evitare di essere eccessivamente istruttivi o di fornire troppi dettagli per non limitare la creatività del modello e la diversità delle risposte.
e.Il linguaggio è conciso e chiaro: scrivere le istruzioni in un linguaggio chiaro, conciso e naturale in modo che il modello possa comprenderle ed elaborarle facilmente.
f. Testare e regolare: Nelle applicazioni del mondo reale, è importante testare e adattare i prompt per garantire che il modello funzioni come previsto e possa gestire una varietà di input in modo efficiente.
Questi principi aiutano a garantire che i modelli linguistici di grandi dimensioni siano efficienti, accurati e creativi nelle loro interazioni con gli utenti.
In breve: il prompt è un punto di partenza, che dà uno spunto, una guida e una standardizzazione al grande modello.
un
ad esempio: fornisci un paragrafo e chiedi a GPT di riassumerlo. In questo esempio utilizziamo ``` come delimitatore.
- 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.Output strutturato
es: Genera i titoli, gli autori e le categorie di tre libri e li restituisce in formato JSON Per facilitare l'analisi, specifichiamo le chiavi Json: book_id, titolo, autore, genere.
- prompt = f"""请生成包括书名、作者和类别的虚构的、非真实存在的中文书籍清单,并以 JSON 格式
- 提供,其中包含以下键:book_id、title、author、genre。"""
- response = get_completion(prompt)
- print(response)
- [
- { "book_id": 1, "title": "幻境之夜", "author": "李梦飞", "genre": "奇幻小说"
- },
- ... ]
c.Esempio di riferimento
Suggerimenti per lo scatto zero:Il modello genera risposte solo in base alla descrizione dell'attività e non richiede alcun esempio.
Suggerimenti a colpo singolo:Viene fornito un solo esempio.
Suggerimenti per pochi scatti: Fornire alcuni esempi. Il ruolo dei prompt è guidare il modello ad apprendere ed eseguire attività specifiche attraverso un numero limitato di campioni. Ad esempio, fornendo un numero limitato di esempi di stili o temi, guida il modello a produrre creazioni con stili o temi simili.
d. Lasciare che il modello agisca come un ruolo
Esempio : Per favore, spiega "Essere o non essere, questo è il problema" come Amleto dall'opera di Shakespeare. Questo esempio richiede che il modello interpreti la famosa domanda "essere o non essere" utilizzando il ruolo del protagonista nell'opera di Shakespeare "Amleto" per dimostrare la performance del modello e la comprensione contestuale in diversi ruoli.
Compiti del progetto(Tre principali scenari aziendali):
1. Classificazione del testo
2. Estrazione delle informazioni di testo
3.Corrispondenza del testo
Ampia selezione di modelli:ChatGLM-6B
metodi di adattamento: Sulla base delle idee di Few-Shot+Zero-Shot e Instrunction, progetta il prompt e quindi applica il modello ChatGLM-6B per completare le attività corrispondenti.
a. Usiamo l'ambiente Python per eseguire modelli di grandi dimensioni, quindi dobbiamo prima scaricare Python (si consiglia anaconda)
b. Scarica il modello del modello ChatGLM-6B, il collegamento è il seguente:
https://github.com/THUDM/ChatGLM-6B?tab=readme-ov-file
Il modello ChatGLM-6B e i requisiti hardware sono introdotti nel README.
Livello quantitativo | Memoria GPU minima(ragionamento) | Memoria GPU minima(Efficiente regolazione fine dei parametri) |
FP16 (senza quantizzazione) | 13 GB | 14 GB |
INT8 | 8 GB | 9 GB |
INT4 | 6 GB | 7 GB |
c. Installa le dipendenze richieste nel tuo anaconda. Nel pacchetto scaricato in precedenza da github, in realtà inserisce tutte le dipendenze richieste in require.txt, inseriscilo direttamente:
pip install -r requisiti.txt
Se la velocità di download è molto lenta, aggiungi il mirror Tsinghua
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
Intransformers
La versione della libreria consigliata è4.27.1
, ma teoricamente non meno di4.23.1
Questo è tutto.
Inoltre, se è necessario eseguire il modello quantizzato sulla CPU, è necessario installare anchegcc
Eopenmp
. La maggior parte delle distribuzioni Linux lo hanno installato di default. Ambiente di prova Windowsgcc
La versione èTDM-GCC 10.3.0
, Linux lo ègcc 11.3.0
。
d. Caricare il modello da locale:
Il codice sopra verrà generato datransformers
Scarica automaticamente l'implementazione e i parametri del modello. L'implementazione completa del modello può essere trovata in Hugging Face Hub. Se l'ambiente di rete è scadente, il download dei parametri del modello potrebbe richiedere molto tempo o addirittura fallire. A questo punto è possibile prima scaricare il modello sul computer locale e poi caricarlo dal computer locale.
Per scaricare il modello da Hugging Face Hub, è necessario prima installare Git LFS e poi eseguirlo
git clone https://huggingface.co/THUDM/chatglm-6b
Se sei lento nel scaricare il checkpoint da Hugging Face Hub, puoi scaricare solo l'implementazione del modello.
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b
Quindi scaricare manualmente il file dei parametri del modello da qui e sostituire il file scaricato in localechatglm-6b
Sotto i contenuti.
Dopo aver scaricato il modello localmente, modificare il fileTHUDM/chatglm-6b
Sostituisci con il tuo localechatglm-6b
Il percorso della cartella per caricare il modello localmente.
MAC Attenzione
Il Mac carica direttamente il modello quantizzato e viene visualizzato il messaggio `clang: errore: opzione non supportata '-fopenmp'.
Ciò è causato dalla mancanza di omp sul Mac stesso, che al momento può essere eseguito ma è single-core. È necessario installare la dipendenza openmp separatamente per utilizzare OMP su 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 /
A questo punto verranno installati i seguenti file:/usr/local/lib/libomp.dylib
, /usr/local/include/ompt.h
, /usr/local/include/omp.h
, /usr/local/include/omp-tools.h
。
NOTA: se in precedenza hai eseguito
ChatGLM
Se il progetto fallisce, è meglio svuotare la cache di Huggingface. L'impostazione predefinita per IE èrm -rf ${HOME}/.cache/huggingface/modules/transformers_modules/chatglm-6b-int4
.a causa dell'utilizzorm
comando, sappi esattamente cosa stai eliminando.
Questa è la soluzione ufficiale, ma non ci sono riuscito. Ho aggiunto quanto segue al codice:
- import os
- os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
Prevenzione degli errori di esecuzione del Mac.
Il nostro scopo è sperare che il modello possa aiutarci a identificare il tipo di rapporto descritto da ciascuna frase di questi quattro paragrafi.
- sentences = [
- "今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。",
- "ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。",
- "公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。",
Per i modelli di grandi dimensioni, la progettazione dei prompt è molto importante. Un prompt chiaro può aiutarci a ottenere meglio i risultati desiderati dai modelli di grandi dimensioni.
Nella progettazione tempestiva di questo compito, consideriamo principalmente due punti:
1. È necessario spiegare al modello cos'è un "attività di classificazione del testo".
2. Il modello deve essere restituito nel formato specificato.
- """
- 利用 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. Fornisci un esempio di alcuni scatti e contrassegna le parole corrispondenti a ciascuna categoria.
b. Memorizzare la categoria in class_list
c. Dare un suggerimento prima che venga fornito il campione. Cioè, racconta il modello. Sei un classificatore di testi, cosa vuoi fare esattamente? e dare una risposta (separata da virgole). (equivalente a una formazione supervisionata)
d. Attraversa gli esempi forniti e aggiungili a pre_history
e. Restituire un dizionario.
I risultati stampati sono i seguenti:
- 分类的类别数:['新闻报道','财务报告','公司公告','分析师报告']
- 键--》新闻报道
- 值--》今日,股市经历了一轮震荡,受到宏观经济数据和全球贸易紧张局势的影响。投资者密切关注美联储可能的政策调整,以适应市场的不确定性。
- 键--》财务报告
- 值--》本公司年度财务报告显示,去年公司实现了稳步增长的盈利,同时资产负债表呈现强劲的状况。经济环境的稳定和管理层的有效战略执行为公司的健康发展奠定了基础。
- 键--》公司公告
- 值--》本公司高兴地宣布成功完成最新一轮并购交易,收购了一家在人工智能领域领先的公司。这一战略举措将有助于扩大我们的业务领域,提高市场竞争力
- 键--》分析师报告
- 值--》最新的行业分析报告指出,科技公司的创新将成为未来增长的主要推动力。云计算、人工智能和数字化转型被认为是引领行业发展的关键因素,投资者应关注这些趋势
- 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)
accedere:
1. Frasi: frasi su cui ragionare.
2. custom_settings: progetto prompt preparato da init_prompts.
processi:
1. Attraversa le frasi che richiedono un ragionamento
2. Esegui il codice principale model.chat(tokenizer, frase_prompt, storia=custom_settings['pre_history'])
In:
Tokenizer: È il tokenizer del codice (può essere inteso come la più piccola unità di una parola)
frase_prompt: integra la frase della domanda in un prompt completato
storia: dichiarazioni storiche precedentemente preparate
Risultati stampati:
- >>>sentence:今天,央行决定通过降低利率来刺激经济增长。这一决策预计会影响到贷款利率,并在接下来的几个季度对金融市场产生深远影响。
- >>>inference answer:新闻报道
- >>>sentence:ABC公司今日宣布,他们已成功收购了XYZ公司的股权。这一重要的收购交易有助于ABC公司扩展业务范围,增强市场竞争力。据悉,这次收购将进一步巩
- 固ABC公司在行业中的地位,并为未来的业务发展提供更广阔的空间。详细信息请参阅公司官方网站公告栏。
- >>>inference answer:公司公告
- ********************************************************************************
- >>>sentence:公司资产负债表显示,公司偿债能力强劲,现金流充足,为未来投资和扩张提供了坚实的财务基础。
- >>>inference answer:财务报告
- ********************************************************************************
- >>>sentence:最新的分析报告指出,可再生能源行业预计将在未来几年经历持续增长,投资者应该关注这一领域的投资机会
- >>>inference answer:分析师报告
Puoi vedere che la classificazione ha successo In questo momento, ho un'idea audace. Cosa succede se digito una frase che non ha nulla a che fare con nessuna delle categorie?
sentences = ["我今天中午和朋友吃了牛肉粉丝汤,不小心洒了一地"]
Verrà stampato come: News Report
A questo punto basta aggiungere:
- "现在你是一个文本分类器,你需要按照要求将我给你的句子分类到:['新闻
- 报道', '财务报告', '公司公告', '分析师报告']类别中。如果都不是就输出:'其他' ",
Il risultato può diventare:
- >>>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
- )
La funzione principale richiama principalmente il tokenizzatore e il modello utilizzato questa volta.
Avviso:
Se selezioni il modello chatglm-6b-int4 durante l'esecuzione su un Mac, verrà segnalato un errore.
- logger.warning("Failed to load cpm_kernels:", exception)
- Message: 'Failed to load cpm_kernels:'
- Arguments: (RuntimeError('Unknown platform: darwin'),)
Se può ancora essere eseguito, non preoccuparti. Se non funziona, passa semplicemente al modello chatglm-6b.
Se desideri utilizzare la GPU per eseguire il modello, puoi sostituirla con questo codice
# model = AutoModel.from_pretrained("./ChatGLM-6B/THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
In effetti, anche l'estrazione delle informazioni di testo è coerente. La cosa principale è implementare la funzione init_prompts e la funzione di inferenza.
- 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. Fornire un esempio di alcuni passaggi per definire gli attributi in entità diverse.
b.Completare la richiesta
c. Aggiungi a ie_pre_history
Stampa come segue:
- _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.Definire l'input:
frasi (List[str]): frasi da estrarre. custom_settings (dict): impostazioni iniziali, inclusi esempi di pochi scatti forniti artificialmente.
b. Definire la categoria: cls_res = "Finanza"
Le categorie sono scritte qui. Se ci sono più categorie. È possibile innanzitutto utilizzare la classificazione del testo per implementarla, quindi estrarre le informazioni di testo.
c. Completa le frasi inserite e chiama model.chat
d. Eseguire la post-elaborazione sui risultati del modello, estrarre il modello JSON e generarlo
Stampa come segue:
- >>> 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
- )
La corrispondenza del testo è specificamente un progetto con il bert che ho fatto prima. Qui utilizziamo principalmente l'implementazione rapida.È sostanzialmente coerente con quanto sopra, quindi non mi concentrerò sull’elaborazione.
Il codice completo è il seguente:
- 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
- )