跳至主要内容

提示压缩:含 Python 示例的指南

提示压缩是在保留语言模型理解并生成相关响应所需关键信息的前提下,缩短输入提示长度的过程。
· 12分钟 阅读

使用 AI 探索

在迅速演进的人工智能领域,优化大型语言模型(LLM)不仅关乎突破可能性的边界,也在于确保效率与成本效益。

提示压缩已成为提升这些模型性能、同时降低计算开销的重要技术。随着新研究几乎每周涌现,紧跟进展颇具挑战,但理解基础原理至关重要。

本文将介绍提示压缩的基础知识,讨论何时应使用、其在降低 RAG 流水线成本方面的重要性,并通过 OpenAI 的 API 提供使用 gpt-3.5-turbo-0125 模型的示例。

如需进一步学习,请查看这门关于提示工程的课程。

什么是提示压缩?

提示压缩是一种用于自然语言处理(NLP)的技术,通过在不显著影响输出质量与相关性的情况下缩短输入到 LLM 的内容长度,以优化输入。之所以需要这种优化,是因为查询中的令牌数量会影响 LLM 的性能。

令牌是 LLM 使用的文本基本单元,代表词或子词,取决于语言模型的分词器。减少提示中的令牌数量有多方面好处,有时甚至是必要的:

  • 令牌上限约束:LLM 的输入有最大令牌上限。超出该上限可能截断重要信息,降低输出清晰度和模型效果。
  • 处理效率与成本降低:更少的令牌意味着更快的处理时间与更低的成本。
  • 提升响应相关性:可读性强的提示并不总等于好提示。有时我们认为良好且信息丰富的提示,对 LLM 来说却包含不重要的信息,例如停用词("a"、"the"、"is" 等)。

提示压缩通过删除冗余信息、概括要点,或利用专门算法提炼提示要义,同时尽量减少令牌数来实现。

我们何时应使用提示压缩?

让我们看看可以使用提示压缩的场景。

高级提示工程技术

诸如思维链(chain-of-thought)提示等技术虽然非常有效,但往往会产生冗长的提示,令牌数可达数千。这会增加处理时间和成本,并可能超过某些模型的令牌上限。

提示压缩通过在保留提示有效性的同时减少令牌数,来缓解这些问题。

检索增强生成(RAG)流水线

RAG 流水线将信息检索与文本生成相结合,常用于上下文理解至关重要的专业聊天机器人和其他应用中。这类流水线常需将大量对话历史或检索到的文档作为提示,导致令牌数很高并推高费用。

在此类场景中,提示压缩对于在保留必要上下文的同时降低成本至关重要。

提示压缩的适用性与局限

需要强调的是,提示压缩并非万能解,应谨慎使用。例如,像 ChatGPT 这类为会话场景设计的助手模型,可能并不适合激进的提示压缩。

这些模型通常不按令牌计费,并内置聊天摘要与记忆功能,以有效管理对话历史,使压缩显得多余。

还需注意,即便在按令牌计费的模型中,过度压缩也可能导致细微差别或重要细节的丢失。在缩小规模与保持提示含义完整之间取得平衡至关重要。

提示压缩如何工作?

提示压缩技术可分为三大类:知识蒸馏、编码与过滤。每种技术都利用不同优势来优化 LLM 提示的长度与效率。

虽然我们会逐一讨论这些技术,但更全面的方法可参见论文:Efficient Prompting Methods for Large Language Models: A Survey。本文将把该论文称为“综述论文”。

知识蒸馏

知识蒸馏是机器学习领域的一种技术,最早由 Hinton 等(2015)提出,即训练一个更小更简单的模型(学生)去复现更大更复杂的模型(教师)的行为。

该技术最初用于应对训练模型集成带来的计算挑战。在提示工程的语境中,知识蒸馏可用于压缩提示而非压缩模型。

其实现方式是通过软提示调整(soft prompt tuning)来学习如何在 LLM 内压缩硬提示。详见综述论文第 3.1 节与附录 A.1.1。

编码

编码方法将输入文本转换为向量,在不丢失关键信息的情况下缩短提示长度。这些向量捕捉提示的核心含义,使 LLM 能够高效处理更短的输入。

不过,取决于编码语言与分词器,令牌长度实际上可能增加。比如,如果将提示用 Base64 编码,令牌长度可能反而更大,因此务必根据您的用例先做一些初步测试。

出人意料的是,一些编码技术也被用于模型越狱,即操纵 LLM 绕过其安全机制。有关编码方法的更多细节,请参见综述论文第 3.2 节与附录 A.1.2。

过滤

前两种方法尝试压缩整个提示,而过滤技术则专注于去除不必要的部分,以提升 LLM 的效率。

过滤技术会评估提示各部分的信息量,并移除冗余内容,因为提示中的信息并非都对 LLM 有益。这可在不同层级上进行,如句子、短语或令牌。

目标是仅保留提示中最相关的部分。在 Li 等(2023)的 Selective Context 一文中,研究者使用自信息度量来过滤冗余信息。在 LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models 一文中,微软研究者将提示精炼为关键组成部分,并为各部分动态调整压缩比。更多内容见综述论文第 3.3 节与附录 A.1.3。

如何用 Python 实现提示压缩

本节我将实现并测试 Selective Context 算法,该算法广受关注,且被认为是当前最先进的方法。如果您只想测试该算法,无需安装任何东西——它已托管在 HuggingFace 平台上。

还有其他主流压缩技术,如 Keep It Simple(KIS)、SCLR,以及 LLMLingua 系列算法,但在这篇短文中无法一一涵盖。

HuggingFace 上 Selective Context 页面截图。

应用链接

在 Selective Context 网页应用中,您可以选择要压缩的提示语言(英文或简体中文)。您还可以设置压缩率,并选择是否按句子、令牌或短语进行过滤。

借助 OpenAI API 实现并测试 Selective Context

现在来进行 Python 实现。我们还将用 gpt-3.5-turbo-0125 模型测试几个压缩后的提示。

首先需要安装所有必需模块。我们要使用 pip 安装 selective-context 库:

pip install selective-context

还需要下载 spacy 的 en_core_web_sm 模型,可通过以下命令完成:

python -m spacy download en_core_web_sm

接着初始化 SelectiveContext 对象。模型可以选择 curie 或 gpt-2,语言可选 en 或 zh。本示例我将使用 gpt-2。

sc = SelectiveContext(model_type = ‘gpt-2’, lang = ‘en’)

然后,我们可以对要压缩的文本字符串调用 SelectiveContext 对象。可设置 reduce_ratio 与 reduce_level 参数。reduce_level 需为以下之一:‘sent’, ‘phrase’ 或 ‘token’。调用将返回一个 (context, reduced_content) 元组,其中 context 为压缩后的提示,reduced_content 为被移除的短语、句子或令牌列表。

context, reduced_content = sc(text, reduce_ratio = 0.5, reduce_level = ‘sent’)

现在做一些示例。我将让 gpt-3.5-turbo-0125 模型总结本文中“我们何时应使用提示压缩”这一节。随后,我们将以 0.5 的压缩率,分别按句子、短语与令牌三个层级进行压缩。我们会再次让模型总结这些压缩版本,并比较各提示的令牌数和模型输出。

原段落与摘要

下方是我将使用的 API 调用——我们只会更改格式化字符串中的 text 变量。首先,请模型总结原始、未压缩的段落:

from openai import OpenAI
client = OpenAI(api_key = key)
completion = client.chat.completions.create(
	model = “gpt-3.5-turbo-0125”,
	messages = [
{“role”: “user”, “content”: f”Summarize the following paragraph:\n {text}”}
]
)

查看 completion.usage 可见原始提示为 304 个令牌,输出如下:

[Prompt compression is useful in scenarios such as advanced prompt engineering techniques and retrieval-augmented generation pipelines to reduce token counts and costs while preserving effectiveness and context. However, it is not a universal solution and should be used judiciously, as excessive compression can lead to a loss of important details. It is important to strike a balance between reducing size and maintaining the prompt's meaning.]

如您所见,模型对未压缩段落的总结相当不错。

令牌级压缩

现在试试令牌级压缩版本。压缩后的段落如下:

[When Should Prompt CompProm compression particularly following Advanced prompt engineering Techniques like chainofthought prompting while highly lengthy prompts reach thousands tokensThis increases processing costs and may exceed token limits of certain modelsProm compression mit these token count while prompt effectivenessRetri-au generationRAG pipelines R combine information retrieval text specialized chat contextual understandingThese pipelines frequently involve providing extensive conversation histories retrieved as prompts leading high token counts increased expensesProm compression essential such essential context while costsApplic prompt compression It prompt universal judFor instance assistant models like ChatGPT designed convers contexts benefit aggressive prompt compressionThese models often do charge per token integrated chat summar memory features conversation history effectively compression redundantIt even working models charge per token excessive compression could nuance importantSt reducing size maintaining prompt’s meaning is]

该提示为 162 个令牌,模型摘要如下:

[Prompt compression is recommended following advanced prompt engineering techniques like chain of thought prompting, especially when dealing with lengthy prompts that reach thousands of tokens. This helps reduce processing costs and ensure that the prompt remains effective for models like RAG pipelines, which involve extensive conversation histories. Prompt compression is essential for maintaining context while keeping costs low, particularly for models like ChatGPT that charge per token and benefit from aggressive compression. However, excessive compression could lead to loss of important nuances, so it is important to strike a balance between reducing size and maintaining the prompt's meaning.]

该摘要并不准确。关于 ChatGPT 不适合激进压缩的细微之处被丢失。

句子级压缩

接着尝试句子级压缩。压缩后的提示为 129 个令牌:

[When Should We Use Prompt Compression? This increases processing times and costs and may exceed token limits of certain models. These pipelines frequently involve providing extensive conversation histories or retrieved documents as prompts, leading to high token counts and increased expenses. Prompt compression is essential in such cases to maintain essential context while minimizing costs. For instance, assistant models like ChatGPT, designed for conversational contexts, may not benefit from aggressive prompt compression. These models often do not charge per token and have integrated chat summarization and memory features to manage conversation history effectively, making compression redundant. ]

模型摘要如下:

[Prompt compression is necessary when processing times, costs, and token limits may be exceeded in pipelines involving extensive conversation histories or retrieved documents as prompts. However, for certain models like ChatGPT, designed for conversational contexts, aggressive prompt compression may not be beneficial as they already have features to manage conversation history effectively without the need for compression.]

该摘要没有错误,但缺少关于 RAG 的讨论。

短语级压缩

最后测试短语级压缩。该提示为 183 个令牌:

[When Should Prompt Compression Prompt compression particularly beneficial Advanced prompt engineering techniques Techniques like chainofthought prompting while highly lengthy prompts reach thousands tokens This increases processing costs and may exceed token limits of certain models Prompt compression these issues token count while the prompt's effectiveness Retrieval-augmented generation (RAG) pipelines RAG pipelines combine information retrieval text generation specialized chatbots contextual understanding These pipelines frequently involve providing extensive conversation histories or retrieved as prompts leading high token counts increased expenses Prompt compression essential such cases to maintain essential context while costs Applicability prompt compression It's For instance assistant models like ChatGPT designed conversational contexts may benefit aggressive prompt compression These models often do charge per token have integrated chat summarization memory features manage conversation history effectively making compression redundant It even working models charge per token excessive compression could nuance important details reducing size maintaining the prompt’s meaning is
]

模型摘要如下:

[Prompt compression is beneficial in advanced prompt engineering techniques, such as chainofthought prompting, which can involve lengthy prompts reaching thousands of tokens. Retrieval-augmented generation (RAG) pipelines combine information retrieval and text generation in specialized chatbots, requiring extensive conversation histories or retrieved prompts leading to high token counts and increased expenses. Prompt compression is essential in maintaining context while managing costs in such cases. For instance, assistant models like ChatGPT, which are designed for conversational contexts, may benefit from aggressive prompt compression to effectively manage conversation history and reduce costs. However, excessive compression could compromise important details, so maintaining the prompt's meaning is crucial.]

该摘要整体正确且连贯。但对 ChatGPT 受益于激进压缩的部分理解有误。

评估提示压缩

通过比较不同压缩层级下的令牌数与模型摘要内容,我们可以看到提示压缩对模型输出的影响:

压缩层级

令牌数(原始为 304)

准确性

令牌级

162

丢失了关于 ChatGPT 不适合激进压缩的重要细微之处,并出现错误。

句子级

129

未出现错误,但遗漏了 RAG 流水线的一些上下文。

短语级

183

与令牌级类似,错误地声称 ChatGPT 受益于激进压缩。

总体来看,提示压缩能在保留核心观点的同时显著降低令牌数。不过,必须把握好平衡,避免丢失重要细节与上下文。

这一练习凸显了需根据具体应用与提示中关键细节的重要性,谨慎选择压缩层级。

值得一提的是,我们所有实验均使用了 0.5 的压缩率,属于相对较高的水平。您或许需要针对不同用例尝试多种压缩率,以在缩小提示规模与保持其完整性之间找到最佳平衡。

结语

提示压缩是一项强大的技术,可用于优化 LLM 的效率与成本效益。我们已探讨其基本原理、重要性、不同技术以及实现细节。

随着生成式 AI 领域不断发展,紧跟最新进展至关重要。为进一步提升您对提示压缩及相关技术的理解与实践,建议查阅本文引用的论文,以及 DataCamp 的以下博文与课程:

提示压缩常见问答

什么是提示压缩?它为何重要?

提示压缩是一种通过缩短输入长度、同时保持输出质量与相关性,以优化输入至大型语言模型(LLM)的技术。其重要性在于帮助遵守令牌上限、减少处理时间与成本。

实现提示压缩时存在哪些常见挑战?

常见挑战包括在压缩与保留关键信息之间保持平衡、处理多样化输入数据类型,以及确保压缩后的提示仍能产生高质量输出。此外,实现基于机器学习或混合方法的方案可能资源开销大且实现复杂。

如何在聊天机器人的多轮对话中处理提示压缩?

对于多轮对话,提示压缩必须确保保留先前交互的上下文。像选择性上下文过滤(selective context filtering)等技术可通过保留对话中的关键信息、压缩次要信息来帮助实现,从而维持聊天机器人的连续性与相关性。

我可以通过哪些资源提升提示压缩技能?

为进一步提升技能,请学习文中引用的研究论文、博文及 DataCamp 课程。主题包括提示工程、提示微调以及检索增强生成(RAG),这些都是掌握提示压缩的关键。同时,务必实践您所学到的技术。

使用提示压缩时是否存在伦理问题?

是的,伦理考量包括确保压缩不会无意中引入偏见或遗漏关键信息,从而导致误导性或有害的输出。此外,提示压缩技术也可能在无意间使模型越狱,导致其行为不可预测或生成不当内容。在医疗、金融或法律建议等敏感应用中,务必监控提示压缩对模型性能与输出的影响。

Dimitri Didmanidze

作者

Dimitri Didmanidze

我叫 Dimitri Didmanidze,是一名数据科学家,目前正在攻读数学硕士学位,研究方向为机器学习。我的学术历程还包括对基于 Transformer 的模型能力进行研究,并在大学层面授课,这些经历加深了我对复杂理论概念的理解。我也曾在银行业工作,将这些原理应用于解决真实世界中的数据难题。

主题