基于 llama2 的提示词工程案例2

优化大型语言模型(LLMs)

优化大型语言模型(LLMs)中的提示词(prompts)是提高模型性能和输出相关性的重要手段。以下是一些优化提示词的方向:

  • 明确性:确保提示词清晰明确,直接指向所需的信息或任务。

  • 上下文提供:在提示词中提供足够的上下文信息,帮助模型更好地理解问题。

  • 简洁性:尽量使提示词简洁,避免不必要的信息,以免造成混淆。

  • 语法正确:使用正确的语法和拼写,因为模型可能会模仿提示词中的语法结构。

  • 使用关键词:在提示词中包含与查询相关的关键词或概念。

  • 避免歧义:尽量避免模糊不清的表述,减少模型产生多种解释的可能性。

  • 指令性:如果需要模型执行特定任务,使用直接的指令性语言。

  • 逐步细化:如果问题复杂,可以将其分解为几个小步骤,在提示词中逐步引导。

  • 使用示例:提供示例或模板,帮助模型理解预期的输出格式。

  • 迭代测试:不断测试和迭代提示词,找到最有效的表达方式。

  • 利用反馈:根据模型的输出反馈调整提示词,以提高其性能。

  • 限制和边界:在需要时,明确提示词中的界限和限制,指导模型生成符合要求的输出。

  • 元提示词:使用元提示词(meta-prompts)来指导模型理解任务的高层次目标。

  • 结合搜索结果:如果模型结合了搜索能力,优化提示词以更好地利用搜索结果。

  • 用户反馈:根据用户反馈调整提示词,以提高用户满意度和模型的实用性。

元提示词

元提示词(Meta-prompts)是一种特殊的提示词,它们不仅提供给语言模型具体的任务或问题,而且还提供关于如何处理这些任务的额外指导或上下文。元提示词可以看作是“关于提示的提示”。

以下是一些元提示词的用途和例子:

  1. List item 任务说明:提供关于所需任务的详细信息。

    • 例子:“请以公正和详细的方式分析这篇文章的论点。”
  2. 格式指导:指定输出的格式或结构。

    • 例子:“请按照以下格式回答:‘问题:[问题内容] 答案:[答案内容]’。”
  3. 风格指导:指示模型采用特定的风格或语调。

    • 例子:“请用技术性的语言回答这个问题,适合发表在学术期刊上。”
  4. 思维过程:引导模型展示其思考或推理过程。

    • 例子:“在提供答案之前,请先概述你的思考过程。”
  5. 详细程度:指示所需的信息量或详细程度。

    • 例子:“请简要描述这个概念,但不要提供过多的技术细节。”
  6. 角色扮演:让模型扮演一个特定的角色或视角。

    • 例子:“以一个5岁孩子的理解水平解释这个科学概念。”
  7. 限制条件:指出在生成回答时需要考虑的限制或约束。

    • 例子:“在不超过5句话的范围内总结这个故事的主要情节。”

代码实现

模型加载

from time import time
import torch
import transformers
from transformers import AutoTokenizer, AutoModelForCausalLM
from IPython.display import display, Markdown
#`IPython`是一个交互式Python环境的增强版,`IPython.display`是其中一个模块,其中的`display`函数和`Markdown`类用于在Jupyter Notebook或IPython环境中展示富文本内容。
from torch import cuda, bfloat16#这里也可以使用auto
#设定使用cpu 还是gpu
device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'#加载本地模型
model = 'D:\临时模型\Meta-Llama-3-8B-Instruct'#加载config 文件
model_config = transformers.AutoConfig.from_pretrained(model,#模型路径trust_remote_code=True,#默认情况下,trust_remote_code 设置为 True。这意味着使用 from_pretrained() 方法加载模型配置文件时,它将下载来自 Hugging Face 模型中心或其他在线资源的配置文件。max_new_tokens=1024 #新生成令牌的数量
)# 加载模型量化
#只有24G的显卡不量化耗时过久
bnb_config = transformers.BitsAndBytesConfig(load_in_4bit=True, # 指定以 4 位精度加载模型bnb_4bit_quant_type='nf4', # 选择使用 NF4(Normal Float 4)数据类型bnb_4bit_use_double_quant=True,# 启用嵌套量化bnb_4bit_compute_dtype=bfloat16 #更改计算期间将使用的数据类型 16位浮点数据类型
)# 加载与模型相匹配的分词器
tokenizer = AutoTokenizer.from_pretrained(model)#实例化模型
model = transformers.AutoModelForCausalLM.from_pretrained(model,#模型的名称或地址trust_remote_code=True,#信任的存储库设置为Trueconfig=model_config, #加载配置文件quantization_config=bnb_config,#加载模型量化device_map='auto',#使用cpu 或GPU
)#构建管道
pipeline = transformers.pipeline("text-generation",model=model,torch_dtype=torch.float16,tokenizer=tokenizer,  # 显式指定分词器device_map=device,
)

模型测试

def query_model(prompt, temperature=0.7,#温度0.7 相对比较活跃的恢复max_length=512):start_time = time()sequences = pipeline(prompt,do_sample=True,#模型将生成确定性的输出,即在给定输入的情况下,每次运行都会产生相同的结果top_k=10,#模型将只考虑概率最高的10个词汇 top_k通常与另一个参数top_p一起使用,temperature=temperature,num_return_sequences=1,#对于给定的输入,生成模型将只产生一个输出序列。eos_token_id=pipeline.tokenizer.eos_token_id,#eos_token通常用于表示句子结束标记max_length=max_length,)answer = f"{sequences[0]['generated_text'][len(prompt):]}\n"end_time = time()ttime = f"Total time: {round(end_time-start_time, 2)} sec."return prompt + " " + answer  + " " +  ttime#美化输出
def colorize_text(text):for word, color in zip(["Reasoning", "Question", "Answer", "Total time"], ["blue", "red", "green", "magenta"]):text = text.replace(f"{word}:", f"\n\n**<font color='{color}'>{word}:</font>**")return text

提示词

prompt = """
You are an AI assistant designed to answer simple questions.
Please restrict your answer to the exact question asked.
Please limit your answer to less than {size} tokens.
Question: {question}
Answer:
"""

你是一个人工智能助理,旨在回答简单的问题。 请将你的答案限制在所问的确切问题上。 请将您的回答限制为小于{size}个tokens。
问题:{问题} 答复

不同token长度和 max_length长度的比对

token大小控制在32

#token大小控制在32
response = query_model(prompt.format(question="What is the surface temperature of the Moon?",#月球表面的温度是多少?size=32), #一个toaken 的大小max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

token大小控制在64

#token大小控制在64
response = query_model(prompt.format(question="What is the surface temperature of the Moon?",#月球表面的温度是多少?size=64), #一个toaken 的大小max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

token大小控制在128

#token大小控制在128
response = query_model(prompt.format(question="What is the surface temperature of the Moon?",size=128), #一个toaken 的大小max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

不采用 prompt.format 不控制token 的情况下输出

#不采用 prompt.format 不控制token 的情况下输出
response = query_model("What is the surface temperature of the Moon?",max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

max_length=128 且 token长度128

response = query_model(prompt.format(question="What is the surface temperature of the Moon?",size=128), #一个toaken 的大小max_length=128)
display(Markdown(colorize_text(response)))

在这里插入图片描述

其他提问的返回

response = query_model(prompt.format(question="Who was the next shogun after Tokugawa Ieyasu?",size=128), #一个toaken 的大小max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

#不采用 prompt.format
response = query_model("Who was the next shogun after Tokugawa Ieyasu?",max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

修改提示词的返回

提示词1

prompt = """
You are an AI assistant designed to write poetry.
Please answer with a haiku format (17 words poems).
Question: {question}
Answer:
"""
response = query_model(prompt.format(question="Please write a poem about Boris Becker wins in tennis",#请写一首关于鲍里斯·贝克尔赢得网球比赛的诗size=256), max_length=256)
display(Markdown(colorize_text(response)))

你是一个人工智能助理,专门用来写诗。 请用俳句形式回答(17个字的诗)。 问题:{问题} 答复
在这里插入图片描述

"""
Golden racket's song Boris Becker's triumphant Victory's sweet echo
金色球拍的歌声鲍里斯·贝克尔胜利的甜蜜回响
"""
response = query_model(prompt.format(question="Please write a poem about Shakespeare being lame at playing poker",#请写一首关于莎士比亚不擅长打扑克的诗size=256), max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

提示词2

prompt = """
You are an AI assistant designed to write poetry.
Please answer with a short poem, with rime, in the style of Shakespeare's poems.
Question: {question}
Answer:
"""
response = query_model(prompt.format(question="Please write a poem about Nadia Comaneci winning Montreal Olympiad",size=256), max_length=256)
display(Markdown(colorize_text(response)))

你是一个人工智能助理,专门用来写诗。 请用莎士比亚诗歌风格的带有雾凇的短诗来回答。 问题:{问题} 答复
在这里插入图片描述

提示词3

prompt = """
You are an AI assistant designed to write simple Python code.
Please answer with the listing of the Python code.
Question: {question}
Answer:
"""
response = query_model(prompt.format(question="Please write a function in Python to calculate the area of a circle of radius r",size=256), max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

代码能力的测试

prompt = """
You are an AI assistant designed to write simple Python code.
Please answer with the listing of the Python code.
Question: {question}
Answer:
"""
response = query_model(prompt.format(question="Please write a function in Python to calculate the area of a circle of radius r",size=256), max_length=256)
display(Markdown(colorize_text(response)))

在这里插入图片描述

response = query_model(prompt.format(question="""Please write a class in Python to model a phone book (storing name, surname, address, phone) with add, delete, order by name, search operations.The class should store a list of contacts, eachwith name, surname, address, phone information stored.""",size=1024), max_length=1024)
display(Markdown(colorize_text(response)))

在这里插入图片描述
以上是文本的全部内容,感谢阅读。

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

javaWeb入门(自用)

1. vue学习 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title><script src"https://unpkg.com/vue2"></script> </head> <body><div id"…

linux上如何排查JVM内存过高?

怎么排查JVM内存过高&#xff1f; 前言&#xff1a; 想必工作一两年以后的同学都会逐渐面临到&#xff0c;jvm等问题&#xff0c;但是可能苦于无法熟练的使用一些工具&#xff1b;本文将介绍几个比较常用分析工具的使用方法&#xff0c;带着大家一步步定位分析问题。 1、top 查…

【大模型】LLaMA-1 模型介绍

文章目录 一、背景介绍二、模型介绍2.1 模型结构2.2 模型超参数2.3 SwiGLU 三、代码分析3.1 模型结构代码3.2 FairScale库介绍 四、LLaMA家族模型4.1 Alpaca4.2 Vicuna4.3 Koala(考拉)4.4 Baize (白泽)4.5 Luotuo (骆驼&#xff0c;Chinese)4.6 其他 参考资料 LLaMA&#xff08…

05-08 周三 FastBuild FastAPI 引入并发支持和全局捕获异常

时间版本修改人描述2024年5月8日20:41:03V0.1宋全恒新建文档 简介 由于FastBuild之前花费了大概5天的时间优化&#xff0c;但最近重新部署&#xff0c;又发现了一些问题&#xff0c;就很痛苦&#xff0c;五一之后&#xff0c;自己又花了三天的时间系统的进行了优化。 上一波优…

历代著名画家作品赏析-东晋顾恺之

中国历史朝代顺序为&#xff1a;夏朝、商朝、西周、东周、秦朝、西楚、西汉、新朝、玄汉、东汉、三国、曹魏、蜀汉、孙吴、西晋、东晋、十六国、南朝、刘宋、南齐、南梁、南陈、北朝、北魏、东魏、北齐、西魏、北周、隋&#xff0c;唐宋元明清&#xff0c;近代。 一、东晋著名…

qt开发解压缩zip文件实现

作者开发环境&#xff1a;Qt5.8 &#xff0c;win10 总体思路&#xff1a;首先我们编译zip源码&#xff0c;生成zip的动态库&#xff1b;然后再编译quazip源码&#xff0c;得到quazip的动态库&#xff1b;最后在我们的程序中去调用。 详细步骤&#xff1a; 1、编译zlib zlib…

sourceTree push失败

新电脑选择commit and push&#xff0c;报错了&#xff0c;不过commit成功&#xff0c;只不过push失败了。 原因是这个&#xff0c;PuTTYs cache and carry on connecting. 这里的ssh选择的是 PuTTY/Plink&#xff0c;本地没有这个ssh密钥&#xff0c;改换成openSSH&#xff…

链表的阶乘

int FactorialSum(List L) {int res 0; // 结果初始化struct Node* x L; // 从链表的头节点开始// 遍历链表中的每一个节点while (x ! NULL) {int data x->Data; // 当前节点的值int y 1; // 用于计算当前节点值的阶乘// 计算当前节点值的阶乘for (int j 1; j < dat…

TCP四次挥手中为什么 TIME_WAIT 等待的时间是 2MSL?

TCP 连接断开 1、TCP 四次挥手过程是怎样的&#xff1f;如下图 2、为什么 TIME_WAIT 等待的时间是 2MSL&#xff1f; MSL 是 Maximum Segment Lifetime&#xff0c;报文最大生存时间&#xff0c;它是任何报文在网络上存在的最长时间&#xff0c;超过这个时间报文将被丢弃。因…

【工具推荐定制开发】一款轻量的批量web请求命令行工具支持全平台:hey,基本安装、配置、使用

背景 在开发 Web 应用的过程中&#xff0c;作为开发人员&#xff0c;为了确认接口的性能能够达到要求&#xff0c;我们往往需要一个接口压测工具&#xff0c;帮助我们快速地对我们所提供的 Web 服务发起批量请求。在接口联调的过程中&#xff0c;我们通常会用 Postman 等图形化…

MVC与MVVM架构模式

1、MVC MVC&#xff1a;Model-View-Controller&#xff0c;即模型-视图-控制器 MVC模式是一种非常经典的软件架构模式。从设计模式的角度来看&#xff0c;MVC模式是一种复合模式&#xff0c;它将多个设计模式结合在一种解决方案中&#xff0c;从而可以解决许多设计问题。 MV…

C++:类与对象—继承

类与对象—继承 一、继承是什么&#xff1f;二、继承定义三、基类和派生类对象赋值转换四、继承中的作用域五、派生类的默认成员函数六、继承与友元七、继承与静态成员八、复杂的菱形继承及菱形虚拟继承九、继承的总结和反思十、考察重点 一、继承是什么&#xff1f; 继承(inh…