Skip to content
quboliu
Go back

Repost · Bilingual

Prompt caching: 10x cheaper LLM tokens, but how?提示词缓存:LLM 的输入 token 为什么能便宜十倍?

Area: AI 与 AgentEdit page

Prompt caching is when an LLM provider reuses work the model already did on the start of a prompt, for any later request that begins with the same tokens. As I write this post, cached input tokens are 10x cheaper in dollars per token than regular input tokens for both OpenAI and Anthropic’s APIs.

提示词缓存是指,当新请求与先前的提示词以同一串 token 开头时,LLM 服务商可以复用模型处理这段前缀时已经完成的计算。在我写这篇文章时,OpenAI 和 Anthropic 的 API 对缓存输入 token 的收费都是常规输入 token 的十分之一。

Anthropic even claim that prompt caching can reduce latency “by up to 85% for long prompts” and in my own testing I found that for a long enough prompt, this is true. I sent hundreds of requests to both Anthropic and OpenAI and noticed a substantial reduction in time-to-first-token latency for prompts where every input token was cached.

Anthropic 甚至声称提示词缓存能将长提示词的延迟”降低多达 85%“,而在我自己的测试中,对于足够长的提示词,这确实成立。我向 Anthropic 和 OpenAI 发送了数百个请求,发现在所有输入令牌均被缓存的情况下,首令牌延迟时间显著减少。

GPT-5:不同提示长度下的首 token 延迟
GPT-5: time to first token by prompt length
GPT-5:不同提示长度下的首 token 延迟
Sonnet 4.5:不同提示长度下的首 token 延迟
Sonnet 4.5: time to first token by prompt length
Sonnet 4.5:不同提示长度下的首 token 延迟

Now that I’ve hooked you in with fancy gradient text and pretty charts, have you ever asked yourself…

既然我已经用花哨的渐变文字和漂亮的图表吸引了你的注意,你是否曾问过自己…

What on earth is a cached token?

缓存的令牌究竟是什么?

What’s going on in those vast oceans of GPUs that enables providers to give you a 10x discount on input tokens? What are they saving between requests? It’s not a case of saving the response and re-using it if the same prompt is sent again, it’s easy to verify that this isn’t happening through the API. Write a prompt, send it a dozen times, notice that you get different responses each time even when the usage section shows cached input tokens.

那些庞大的 GPU 海洋中究竟发生了什么,让供应商能为你的输入令牌提供 10 倍折扣?他们在请求之间节省了什么?这并非保存响应并在再次发送相同提示时重复使用那么简单——通过 API 很容易验证这种情况并未发生。编写一个提示,发送十几次,你会发现每次得到的响应都不同,即使 usage 部分显示的是缓存的输入令牌。

Not satisfied with the answers in the vendor documentation, which do a good job of explaining how to use prompt caching but sidestep the question of what is actually being cached, I decided to go deeper. I went down the rabbit hole of how LLMs work until I understood the precise data providers cache, what it’s used for, and how it makes everything faster and cheaper for everyone.

我对供应商文档中的解答并不满意,它们虽然很好地解释了如何使用提示缓存,却回避了真正缓存内容的问题,因此决定深入研究。我深入探索了 LLMs 的工作机制,直到理解了数据提供商缓存的具体内容、其用途,以及它如何为所有人实现更快速、更低廉的服务。

By the end of this post you will…

读完本文,你将能做到以下几点。

LLM architecture大语言模型架构

At their core, LLMs are giant mathematical functions. They take a sequence of numbers as input, and produce a number as output. Inside the LLM there is an enormous graph of billions of carefully arranged operations that transform the input numbers into an output number.

LLM 的核心是巨型数学函数。它们接收一系列数字作为输入,并产生一个数字作为输出。LLM 内部包含一个由数十亿个精心编排的操作构成的庞大计算图,这些操作将输入数字转换为输出数字。

This enormous graph of operations can be roughly split into 4 parts.

这个庞大的操作计算图大致可分为四个部分。

大语言模型的推理循环
The LLM inference loop
大语言模型的推理循环

Each node in that diagram can be thought of as a function that takes some input, and produces some output. Input is fed into the LLM in a loop until a special output value tells it to stop. Here’s how it might look as pseudocode:

图中每个节点可视为一个函数,接收特定输入并产生输出。输入内容会在循环中持续馈入 LLM,直到某个特殊输出值通知其停止。以下为对应的伪代码示意:

prompt = "What is the meaning of life?";

tokens = tokenizer(prompt);
while (true) {
	embeddings = embed(tokens);
	for ([attention, feedforward] of transformers) {
		embeddings = attention(embeddings);
		embeddings = feedforward(embeddings);
	}
	output_token = output(embeddings);
	if (output_token === END_TOKEN) {
		break;
	}
	tokens.push(output_token);
}

print(decode(tokens));

LLMs are surprisingly small大语言模型的实现可以很短

While the above is greatly simplified, it surprised me just how few lines of code modern LLMs have.

虽然以上内容经过大幅简化,但现代 LLM 的代码行数之少仍然令我惊讶。

Sebastian Raschka creates standalone reimplementations of open source models using PyTorch, as well as a tonne of other top-tier educational material that you’ll enjoy if you like this post. One of the current leading open models, Olmo 3, comes in at only a couple hundred lines of code for example.

Sebastian Raschka 使用 PyTorch 对开源模型进行了独立的重新实现,并创作了大量其他顶级教育材料,如果你喜欢这篇文章,你也会喜欢他的作品。以当前领先的开源模型之一 Olmo 3 为例,其核心代码只有寥寥几百行。

The place where prompt caching happens is in the “attention” mechanism of the transformer. We’re going to walk through how an LLM works, in order, until we get there. That means we have to start this journey by talking about tokens.

提示缓存发生的位置是在 Transformer 的”注意力”机制中。我们将按顺序逐步解析 LLM 的工作原理,直至触及这一环节。这意味着我们必须从讨论”token”开始这段旅程。

Tokenizer分词器

推理循环中的分词阶段
The tokenizer stage
推理循环中的分词阶段

Before the LLM can do anything with your prompt, it needs to convert it into a representation it can work with. This is a two-step process shared between the tokenizer and the embedding stages. It won’t become clear why this is all necessary until we get to embedding, so bear with me while we go through what the tokenizer does.

在 LLM 能处理你的提示词之前,它需要先将提示词转换成可供其处理的表示形式。这是分词器和嵌入层共用的两步流程。要等我们讨论到嵌入时,你才会明白为何这一切是必要的,所以请先耐心听我解释分词器的作用。

The tokenizer takes your prompt, chops it up into small chunks, and assigns each unique chunk an integer ID called a “token.” For example, here’s how GPT-5 tokenizes the prompt “Check out ngrok.ai”:

分词器接收你的提示词,将其切分成小块,并为每个独特的小块分配一个名为”token”的整数 ID。例如,GPT-5 对提示词”Check out ngrok.ai”的分词过程如下:

Token 文本Token ID
Check4383
␣out842
␣ng1657
rok17690
.ai75584

The prompt has been split into the array ["Check", " out", " ng", "rok", ".ai"], and converted into the tokens [4383, 842, 1657, 17690, 75584]. The same prompt always results in the same tokens. Tokens are also case-sensitive, and this is because capitalisation tells you something about the word. “Will” with a capital W is more likely to be a name than “will” with a lowercase W, for example.

提示词已被拆分为数组 ["Check", " out", " ng", "rok", ".ai"] ,并转换为标记 [4383, 842, 1657, 17690, 75584] 。相同的提示词始终产生相同的标记。标记也是区分大小写的,这是因为大小写能传达关于单词的信息。例如,大写 W 开头的 “Will” 更可能是一个名字,而小写 w 开头的 “will” 则不然。

Why not just split on spaces? Or characters?为什么不直接按空格或字符切分?

This is a surprisingly big question, and covering it in detail could easily double the length of this post. The short, unsatisfying answer is that it’s a trade-off. If you want to go deep on it Andrej Karpathy has an excellent video where he builds a tokenizer from scratch. For prompt caching, it’s enough to know that tokenization turns text into numbers.

这是一个出人意料的大问题,详细探讨它很容易让这篇文章的篇幅翻倍。简短且不尽人意的答案是:这是一种权衡。如果你想深入了解,Andrej Karpathy 有一个很棒的视频,他在其中从头开始构建了一个分词器。对于提示词缓存来说,知道分词是将文本转换为数字就足够了。

Tokens are the fundamental unit of input and output for LLMs. When you ask ChatGPT a question, the response is streamed back to you one token at a time as each iteration of the LLM is completed. Providers do this because generating a full response can take tens of seconds, but sending you each token when it’s ready makes the process feel more interactive.

标记是 LLM 输入和输出的基本单位。当你向 ChatGPT 提问时,随着 LLM 的每一轮迭代完成,响应会一次一个标记地流式传回给你。供应商这样做是因为生成完整响应可能需要几十秒,但将每个准备好的标记发送给你,会使整个过程感觉更具交互性。

Let’s ask a classic LLM question to see this in action. Hit the send button below when you’re ready.

让我们来问一个经典的 LLM 问题,看看实际情况。准备好后点击下方的发送按钮。

How many r's in the word 'strawberry'?
5299 (How) · 1991 (␣many) · 428 (␣r) · 885 ('s) · 306 (␣in) · 290 (␣the) · 2195 (␣word) · 461 (␣') · 302 (st) · 1618 (raw) · 19772 (berry) · 127222 ('?)输出

Prompt tokens go in, ✨ AI happens ✨, output token comes out, repeat. This process is called “inference,” and notice that every output token gets appended to the input prompt before the next iteration. LLMs need all of the context to produce good answers. If we only fed the prompt in, it would continually try to produce the first token of the answer. If we only fed the answer in, it would immediately forget the question. The whole prompt + the answer need to be fed into the LLM, every single iteration.

提示词输入,✨AI 进行运算✨,输出词产生,如此循环。这个过程被称为”推理”,请注意每个输出词在下次迭代前都会被追加到输入提示中。LLM 需要完整的上下文才能给出优质回答。如果我们仅输入提示词,模型会持续尝试生成回答的第一个词;如果我们仅输入回答,模型会立刻忘记问题。每一轮迭代都需要将完整的提示词+回答输入给 LLM。

What’s that 199999 <END> token all about?199999 这个 <END> 标记是什么意思?

Inference has to stop at some point. LLMs have a variety of “special” tokens they can output, one of which signals the end of a response. In the GPT-5 tokenizer this is token 199999. This is one of many ways LLMs can terminate. You could specify a maximum number of tokens to generate through the API, and providers may also have other safety-related rules about when to stop.

推理必须在某个点停止。LLMs 可以输出多种“特殊”标记,其中之一就是用来表示响应结束的。在 GPT-5 的分词器中,这个标记是 199999 。这只是 LLMs 能够终止输出的多种方式之一。您可以通过 API 指定要生成的最大标记数量,服务提供商可能还会设置其他与安全相关的规则来决定何时停止。

There are also special tokens for denoting the start and end of conversational messages, and these are how chat models like ChatGPT and Claude know when one message ends and another begins.

此外,还有用于表示对话消息开始和结束的特殊标记,正是通过这些标记,像 ChatGPT 和 Claude 这样的聊天模型才能知道一条消息何时结束,另一条消息何时开始。

Last thing on tokenizers: there are lots of them! The tokenizer that ChatGPT uses is different to the one Claude uses. Even different models made by OpenAI use different tokenizers. Each tokenizer has its own rules for splitting text into tokens. If you want to see how a variety of different tokenizers split text, check out tiktokenizer.

关于分词器的最后一点是:它们有很多种!ChatGPT 使用的分词器与 Claude 使用的不同。即使是 OpenAI 开发的不同模型,也使用不同的分词器。每个分词器都有自己独特的规则来将文本分割成标记。如果您想了解各种不同分词器如何分割文本,可以查看 tiktokenizer。

Now that I’ve introduced you to tokens, let’s talk about embeddings.

现在已经介绍了 token,接下来看看嵌入向量。

Embedding嵌入

推理循环中的嵌入阶段
The embedding stage
推理循环中的嵌入阶段

Our tokens from the tokenizer are now fed into the embedding stage. To understand embedding, it helps to understand what the goal of a model is.

分词得到的 token 接下来进入嵌入阶段。要理解嵌入,可以先想想模型要解决什么问题。

When humans solve a problem with code, we write functions that take input and produce output. Converting Fahrenheit to Celsius, for example.

人写程序解决问题,通常是写一个接收输入、产生输出的函数。比如把华氏温度换算成摄氏温度。

function fahrenheitToCelsius(fahrenheit) {
	return ((fahrenheit - 32) * 5) / 9;
}

We can throw any number into fahrenheitToCelsius and get the right answer. But what if we had a problem where we didn’t know the formula? What if we just had this mysterious table of inputs and outputs below?

我们可以往 fahrenheitToCelsius 里输入任意数字并获得正确答案。但如果我们遇到一个不知道公式的问题呢?如果我们只有下面这个神秘的输入输出表呢?

输入 Input输出 Output
2173
23
1029
2061277

I’m not expecting you to recognise the function here, though I will say that ChatGPT figures it out straight away if you paste a screenshot into the app.

我并不指望你能识别出这里的函数,不过需要说明的是,如果你将截图粘贴到 ChatGPT 应用中,它能立刻推算出来。

When we know the expected output for each input, but not the function that produces it, we can “train” a model to learn the function. We do this by giving the model a canvas—the enormous graph of mathematical operations—and modifying that graph until the model converges on the correct function. Every time the graph is updated, we run the inputs through it to see how close it gets to the correct outputs. We do this until we’re happy it’s close enough. This is what training is.

当我们已知每个输入对应的预期输出,但不知道生成该输出的函数时,我们可以通过”训练”模型来学习这个函数。具体做法是为模型提供一个画布——即庞大的数学运算图——并通过不断修改这个图,直到模型收敛到正确的函数。每次更新运算图后,我们都会用输入数据测试其输出结果与正确输出的接近程度,如此反复直至达到令人满意的近似精度。这个过程就是所谓的模型训练。

It turns out, when training a model to output correct text, it helps to be able to recognise when two sentences are similar. Similar how, though? They may be similarly sad, or funny, or thought-provoking. They may be similar in length, rhythm, tone, language, vocabulary, structure. There are a huge number of dimensions that we can use to describe the similarity of two sentences, and sentences can be similar along some dimensions but not others.

事实上,在训练模型输出正确文本时,能够识别两个句子的相似程度会很有帮助。但具体指哪方面的相似呢?可能它们在悲伤、有趣或发人深省的情感上相近,也可能在长度、韵律、语调、语言、词汇或结构方面相似。我们可用大量维度来描述两个句子的相似性,而句子可能在某些维度上惊人地相似,在其他维度上却截然不同。

Tokens do not have dimensions. They’re plain ol’ integers. Embeddings, though, embeddings have lots of dimensions.

词元本身没有维度——它们就是单纯的整数。但嵌入则不同,嵌入拥有许多维度。

An embedding is an array of length n representing a position in n-dimensional space. If n were 3, an embedding might be [10, 4, 2] representing the location x=10, y=4, z=2 in 3 dimensional space. When LLMs are being trained, each token gets assigned a random starting location in this space, and the training process nudges all of the tokens around until it finds an arrangement that produces the best outputs.

嵌入是一个长度为 n 的数组,代表着 n 维空间中的一个位置。如果 n 为 3,那么一个嵌入可能是 [10, 4, 2] ,对应着三维空间中的坐标 x=10, y=4, z=2 。在训练 LLMs 时,每个词元会被随机分配到这个空间中的一个起始位置,随后训练过程会微调所有词元的位置,直到找到能产生最佳输出的排列方式。

The embedding stage starts out by looking up each token’s embedding. In pseudocode it might look like this:

嵌入阶段首先通过查表获取每个词元的嵌入向量。用伪代码表示大致如下:

// Created during training, never changes during inference.
const EMBEDDINGS = [...];

function embed(tokens) {
	return tokens.map(token => {
		return EMBEDDINGS[token];
	});
}

So we take tokens, an array of integers, and convert it into an array of embeddings. An array of arrays, or a “matrix.” Toggle between tokens and embeddings below to see how I picture this process in my head.

我们接收一个整数数组 tokens ,将其转换为嵌入向量数组——也就是数组的数组,或者说“矩阵”。您可以通过下方切换按钮在词元与嵌入向量视图间切换,这正对应着我脑海中构想的转换过程。

75, 305, 284, 887

The tokens [75, 305, 284, 887] get converted into a matrix of 3-dimensional embeddings.

tokens [75, 305, 284, 887] 被转换成三维嵌入矩阵。

The more dimensions we give the embeddings, the more dimensions it has to compare sentences with. We’ve been talking about embeddings with 3 dimensions, but current models have embeddings with thousands of dimensions. The biggest ones have more than 10,000.

我们赋予嵌入的维度越多,它用于比较句子的维度就越多。我们一直在讨论三维嵌入,但当前模型的嵌入具有数千个维度。规模最大的模型甚至超过一万维。

To demonstrate the value of more dimensions, below I have 8 groups of coloured shapes that start off in 1-dimensional space. They sit on a line, and they’re a jumbled mess that’s hard to make sense of. But as you add more dimensions, it becomes clear that there are 8 distinct, related groups. Click the 2D and 3D buttons to see what I mean.

为了展示更多维度的价值,下面我展示了从一维空间开始的八组彩色形状。它们排列在一条直线上,呈现出一团混乱、难以理解的景象。但随着维度的增加,可以清楚地看到八个不同但相关的组别。点击 2D 和 3D 按钮就能明白我的意思。

八组形状投影在一条轴上

3 dimensions is the best I can do for a visual example here, you’ll have to use your imagination to picture what you might be able to do with thousands of dimensions.

我最多只能用三维来做视觉示例,要想象数千维度能做什么,还得靠您自己发挥想象力。

There’s one last thing that the embedding stage does. After fetching a token’s embeddings, it encodes the token’s position within the prompt into the embeddings. I didn’t dig deeply into how this works other than enough to know it doesn’t make much difference to how prompt caching works, but without it the LLM would not be able to tell the order of the tokens in the prompt.

嵌入阶段还有最后一项功能。在获取词元的嵌入向量后,它会将词元在提示词中的位置信息编码到嵌入向量中。我没有深入研究其具体实现原理,只了解到这对提示词缓存的工作方式影响不大;但如果没有这个步骤,LLM 将无法识别提示词中词元的顺序。

To update our pseudocode from earlier, assume that a function called encodePosition exists. It takes embeddings and a position and returns new embeddings with the position encoded within.

更新我们之前的伪代码:假设存在一个名为 encodePosition 的函数。该函数接收嵌入向量和位置参数,并返回编码了位置信息的新嵌入向量。

const EMBEDDINGS = [...];

// Input: array of tokens (integers)
function embed(tokens) {
	// Output: array of n-dimensional embedding arrays
	return tokens.map((token, i) => {
		const embeddings = EMBEDDINGS[token];
		return encodePosition(embeddings, i);
	});
}

In summary, embeddings are points in n-dimensional space that you can think of as the semantic meaning of the text they represent. During training, each token gets moved within this space to be close to other, similar tokens. The more dimensions, the more complex and nuanced the LLM’s representation of each token can be.

简言之,嵌入是 n 维空间中的点,可将其视为所代表文本的语义含义。在训练过程中,每个标记会被移至此空间内,以便靠近其他相似的标记。维度越多,LLM 对每个标记的表征就能越复杂和精细。

All of the work we’ve done in the tokenizer and embedding stages has been to convert text into something the LLM can work with. Let’s now take a look at what that work looks like in the transformer stage.

我们在分词器和嵌入阶段所做的全部工作,都是为了将文本转化为 LLM 能够处理的形式。现在让我们来看看在 Transformer 阶段,这些工作具体是如何展开的。

TransformerTransformer 层

推理循环中的 Transformer 阶段
The transformer stage
推理循环中的 Transformer 阶段

The transformer stage is all about taking embeddings as input and moving them around their n-dimensional space. It does this in two ways, and we’re only going to focus on the first: attention. We aren’t going to talk about “Feedforward” or the output stage (in this post 👀).

Transformer 阶段的核心在于接收嵌入作为输入,并在其 n 维空间中进行移动调整。此过程通过两种方式实现,而我们只聚焦于第一种:注意力机制。本文将不讨论”前馈网络”或输出阶段(本文暂不涉及👀)。

The job of the attention mechanism is to help the LLM understand the relationships between each token in the prompt, by allowing tokens to influence each others’ positions in n-dimensional space. It does this by combining the embeddings of the prompt’s tokens in a weighted fashion. The input is an entire prompt’s embeddings, and the output is a single new embedding that is a weighted combination of all of the input embeddings.

注意力机制的作用是帮助 LLM 理解提示中每个标记之间的关系,其方式是通过让标记在 n 维空间中相互影响彼此的位置来实现的。这是通过以加权方式组合提示标记的嵌入表示来完成的。输入是整个提示的嵌入表示,输出则是一个单一的新的嵌入表示,它是所有输入嵌入表示的加权组合。

For example, if we had the prompt “Mary had a little”, and it resulted in the 4 tokens Mary, had, a, and little, the attention mechanism might decide that to generate the next token we should use:

例如,假设我们有提示 “Mary had a little”,它产生了四个标记 Mary 、 had 、 a 和 little ,那么注意力机制可能会决定,要生成下一个标记,我们应该使用:

And it would combine them all by scaling them by their weights and summing them up. This is how LLMs know how much they should care about, or “attend” to, each token in a prompt.

它会通过按权重缩放这些值并将它们相加来组合所有嵌入。这就是 LLMs 知道应该对提示中的每个 token 给予多少关注(或”attend”)的方式。

This is the most complicated and abstract part of the process so far. I’m going to present it first as pseudocode, and then we’ll have a look at how the embeddings get manipulated passing through it. I wanted to make this section less math-heavy but it’s hard to avoid some math here. You can do it, I believe in you.

这是目前过程中最复杂和抽象的部分。我将首先以伪代码的形式呈现,然后我们会看看嵌入在通过这个过程时是如何被操作的。我本想让这部分少一些数学内容,但这里很难完全避免数学。你可以做到的,我相信你。

Most of the calculations in attention are matrix multiplications. The only thing you need to know about matrix multiplication for this post is that the shape of the output matrix is determined by the shapes of the input matrices. The output always has the same number of rows as the first input matrix and the same number of columns as the second input matrix.

注意力机制中的大部分计算都是矩阵乘法。关于矩阵乘法,本文只需了解:输出矩阵的形状由输入矩阵的形状决定。输出矩阵的行数始终与第一个输入矩阵的行数相同,列数始终与第二个输入矩阵的列数相同。

2x3
1.002.003.00
4.005.006.00
×
3x1
6.00
7.00
8.00
=
2x1
44.00
107.00

With that in mind, here’s how a simplified attention mechanism calculates the weight to assign to each token. In the code below I’m using * to represent matrix multiplication.

基于这一点,下面是一个简化的注意力机制如何计算每个令牌权重的过程。在以下代码中,我用 * 来代表矩阵乘法。

// Similar to EMBEDDINGS from the pseudocode
// earlier, WQ and WK are learned during
// training and do not change during inference.
//
// These are both n*n matrices, where n is the
// number of embedding dimensions. In our example
// above, n = 3.
const WQ = [[...], [...], [...]];
const WK = [[...], [...], [...]];

// The input embeddings look like this:
// [
//   [-0.1, 0.1, -0.3], // Mary
//   [1.0, -0.5, -0.6], // had
//   [0.0, 0.8, 0.6],   // a
//   [0.5, -0.7, 1.0]   // little
// ]
function attentionWeights(embeddings) {
	const Q = embeddings * WQ;
	const K = embeddings * WK;
	const scores = Q * transpose(K);
	const masked = mask(scores);
	return softmax(masked);
}

Let’s take a look at the embeddings as they flow through this function.

让我们来看一看嵌入是如何通过这个函数流动的。

Hold up, what’re these WQ and WK variables?等一下,WQ 和 WK 是什么?

Remember how I said earlier that the embeddings for each token get assigned a random position and then the training process makes small tweaks to them until the model converges on a good arrangement?

还记得我之前提到的吗?每个令牌的嵌入会被分配一个随机位置,然后训练过程会对它们进行微调,直到模型达到理想的排布?

WQ and WK are similar. They’re n-by-n matrices, with n being the embedding dimension, and they’re given random values at the start of training. Then during training they also get tweaked to help the model converge on a good solution.

WQ 和 WK 是相似的。它们是 n × n 的矩阵,其中 n 代表嵌入维度,在训练开始时被赋予随机值。随后在训练过程中,它们也会被微调以帮助模型收敛到一个好的解决方案。

Anything that gets tweaked during training is said to be a “model parameter.” Each floating point number in the embeddings vectors and inside these WQ and WK matrices is one parameter. When you hear a model being described as having “175 billion parameters,” these are the numbers they’re talking about.

在训练过程中被微调的任何内容都被称为“模型参数”。嵌入向量以及这些 WQ 和 WK 矩阵中的每个浮点数都是一个参数。当你听说某个模型具有“1750 亿参数”时,指的就是这些数字。

As for what WQ and WK actually are, we kinda don’t know. As the model converges, they end up representing some kind of transformation of the embeddings that helps the model produce good output. They could be doing anything, and interpreting what’s in there is an open and active area of research.

至于 WQ 和 WK 实际上是什么,我们并不完全清楚。随着模型收敛,它们最终代表了嵌入的某种变换,帮助模型产生良好的输出。它们可能执行任何操作,而解读其中的内容是一个开放且活跃的研究领域。

To get Q and K we take embeddings and multiply them by WQ and WK respectively. WQ and WK always have rows and columns equal to the number of embedding dimensions, which is 3 in this case. I’ve picked random values for WQ and WK here, and values are rounded to 2 decimal places for readability.

为了得到 Q 和 K ,我们取 embeddings 并分别乘以 WQ 和 WK 。 WQ 和 WK 的行数和列数总是等于嵌入维度的数量,在这里是 3。我为 WQ 和 WK 选择了随机值,并且为了可读性,数值都保留两位小数。

embeddings
-0.060.13-0.30
0.95-0.49-0.64
-0.050.750.65
0.51-0.720.98
×
WQ
-0.740.91-0.21
-0.510.430.18
-0.56-0.210.76
=
Q
0.150.07-0.19
-0.100.79-0.78
-0.710.150.64
-0.56-0.060.51

The resulting Q matrix has 4 rows and 3 columns. 4 rows because the embeddings matrix had 4 rows (one per token), and 3 columns because WQ had 3 columns (one per embedding dimension).

生成的 Q 矩阵有 4 行和 3 列。之所以有 4 行,是因为嵌入矩阵有 4 行(每个标记对应一行),而有 3 列是因为 WQ 有 3 列(每个嵌入维度对应一列)。

The calculation for K is exactly the same, just with WK instead of WQ.

K 的计算方式完全相同,只需要将 WQ 替换为 WK 即可。

embeddings
-0.060.13-0.30
0.95-0.49-0.64
-0.050.750.65
0.51-0.720.98
×
WK
0.13-0.51-0.63
-0.790.54-0.04
0.33-0.10-0.87
=
K
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15

Q and K are both “projections” of the input embeddings into new n-dimensional spaces. They’re not the original embeddings, but they’re derived from them.

Q 和 K 都是将输入嵌入向量“投影”到新的 n 维空间的结果。它们并非原始嵌入向量,而是衍生于这些向量的新表示。

Then we take Q and K and multiply them together. We “transpose” K, which means we flip it along the diagonal, so that the resulting matrix is a square, with rows and columns equal to the number of tokens in the input prompt.

然后,我们取 Q 和 K 并将它们相乘。我们“转置” K ,这意味着我们沿着对角线翻转它,使得结果矩阵是一个方阵,行和列的数量等于输入提示中的词元数量。

Q
0.150.07-0.19
-0.100.79-0.78
-0.710.150.64
-0.56-0.060.51
×
transpose(K)
-0.210.30-0.390.96
0.13-0.680.36-0.74
0.29-0.03-0.56-1.15
=
scores
-0.080.000.080.31
-0.10-0.540.760.21
0.36-0.33-0.04-1.53
0.26-0.15-0.09-1.08

These scores are a representation of how important each token is to the next token generated. The top left number, -0.08, is how important “Mary” is to “had”. Then 1 row down, -0.10, is how important “Mary” is to “a”. I’ll show a visual of this after the matrix math. Everything that happens next is about turning these scores into weights that we can use to mix the embeddings together.

这些 scores 代表着每个 token 对下一个生成的 token 的重要性。左上角的数字 -0.08 表示”Mary”对”had”的重要性。向下第一行的 -0.10 则表示”Mary”对”a”的重要性。在矩阵运算之后,我将用图示展示这一点。接下来的一切都是关于将这些分数转化为我们可以用来混合嵌入向量的权重。

The first problem with this matrix of scores is that it allows future tokens to influence the past. In that top row, the only word we know about is “Mary”, so it should be the only word that contributes to the generation of “had”. The same goes for the second row, where we know “Mary” and “had”, so only those two words should contribute to the generation of “a”, and so on.

这个 scores 矩阵的第一个问题在于,它允许未来的 token 影响过去的 token。在第一行中,我们唯一知道的词是”Mary”,所以它应该是唯一对生成”had”有贡献的词。第二行也是如此,我们知道”Mary”和”had”,所以只有这两个词应该对生成”a”有贡献,依此类推。

To fix this, we apply a triangular mask to the matrix to zero out future tokens. Rather than zero them out though, we set them to negative infinity. I’ll explain why in a moment.

为了解决这个问题,我们对矩阵应用一个三角掩码,将未来的 token 置零。不过,我们不是将它们置零,而是将它们设为负无穷大。我稍后会解释原因。

mask(
scores
-0.080.000.080.31
-0.10-0.540.760.21
0.36-0.33-0.04-1.53
0.26-0.15-0.09-1.08
) =
masked
-0.08-∞-∞-∞
-0.10-0.54-∞-∞
0.36-0.33-0.04-∞
0.26-0.15-0.09-1.08

The second problem is that these scores are arbitrary numbers. They would be much more useful to us if they were a distribution that sums to 1 across each row. This is exactly what the softmax function does. The details of how softmax works aren’t important, it’s slightly more complicated than dividing each number by the sum of the row, but the result is the same: each row sums to 1, and each number is between 0 and 1.

第二个问题是这些分数是任意数值。如果它们能形成每行总和为 1 的分布,对我们来说会更加实用。这正是 softmax 函数的功能。 softmax 的具体工作原理细节并不重要,它比简单地将每个数值除以行总和略复杂,但结果相同:每行总和为 1,且每个数值都在 0 到 1 之间。

softmax(
masked
-0.08-∞-∞-∞
-0.10-0.54-∞-∞
0.36-0.33-0.04-∞
0.26-0.15-0.09-1.08
) =
weights
1.000.000.000.00
0.610.390.000.00
0.460.230.310.00
0.380.250.270.10

To explain the negative infinities, here’s an implementation of softmax in code:

为了解释负无穷大,以下是 softmax 的代码实现:

function softmax(matrix) {
	return matrix.map(row => {
		const exps = row.map(x => Math.exp(x));
		const sumExps = exps.reduce((a, b) => a + b, 0);
		return exps.map(exp => exp / sumExps);
	});
}

It doesn’t quite sum the numbers and then divide each number by the sum. Instead, it takes the Math.exp of each number first, which does e^x. If we used zeroes instead of negative infinity, Math.exp(0) === 1 so the zeroes would still contribute a weight. Math.exp(-Infinity) is 0, which is what we want.

它先对每个数求指数(Math.exp),然后把每项除以所有指数的和。这样既能把权重归一化,也解释了为什么前面要用负无穷大:如果填的是零,exp(0)=1 仍会占到权重;负无穷大的指数才是零。

The grid below shows an example of the attention weights for the prompt “Mary had a little”. You can hover or click grid cells to see the contribution each token has. These weights don’t match up with the calculations above because I pulled them from the version of GPT-2 that’s running at the fantastic Transformer Explained site. So these are real weights from a real, albeit old, model.

下面的网格展示了提示词”Mary had a little”的注意力权重示例。您可以悬停或点击网格单元格以查看每个词元所贡献的权重。这些权重与上述计算并不完全吻合,因为它们来自运行在精彩的 Transformer Explained 网站上的 GPT-2 版本。因此,这些权重虽来自一个较旧但真实的模型,却是实际可用的权重数据。

四个提示 token 之间的注意力
Attention across four prompt tokens
四个提示 token 之间的注意力
注意力权重
↘Maryhadalittle
Mary
had
a
little
Mary → lamb · 63%

In the first row, we just have “Mary”, so Mary contributes 100% to “had”. Then in the 2nd row “Mary” contributes 79% while “had” contributes 21% to the generation of “a”, and so on. It’s probably not surprising that the word the LLM thinks is most important in this sentence is “Mary,” as shown by Mary having the highest weight in every row. If I asked you to complete the sentence “Jessica had a little” it’s unlikely you’d pick “lamb.”

第一行中只有”玛丽”,所以”玛丽”对”had”的贡献度是 100%。接着在第二行,“玛丽”贡献了 79%,而”had”对生成”a”贡献了 21%,依此类推。或许并不意外,LLM 认为这句话中最重要的词是”玛丽”,因为”玛丽”在每一行的权重都是最高的。如果我让你补全”杰西卡有一只小”这句话,你很可能不会选择”羔羊”。

All that remains is to do the mixing of the token embeddings, which is mercifully simpler than generating the weights.

剩下要做的就是混合词元嵌入,值得庆幸的是,这比生成权重要简单得多。

// Learned during training, doesn't change
// during inference. This is also an n*n matrix,
// where n is the number of embedding dimensions.
const WV = [[...], [...], ...];

function attention(embeddings) {
	const V = embeddings * WV;
	// This is the `attentionWeights` function from
	// the section above. We're wrapping it in
	// this `attention` function.
	const weights = attentionWeights(embeddings);
	return weights * V;
}

Similar to before, we have a WV matrix that’s determined at training time. We use this to get a V matrix from the token embeddings.

与之前类似,我们有一个在训练时确定的 WV 矩阵。我们用它从词元嵌入中获取一个 V 矩阵。

embeddings
-0.060.13-0.30
0.95-0.49-0.64
-0.050.750.65
0.51-0.720.98
×
WV
0.960.62-0.40
-0.900.06-0.55
-0.17-0.090.59
=
V
-0.12-0.00-0.23
1.460.62-0.49
-0.83-0.04-0.01
0.970.180.78

Why not mix the embeddings directly?为什么不直接混合嵌入向量?

When we derive Q and K then multiply them together to get the attention weights, we’re operating entirely on the relevance tokens have to each other. Embeddings are encoding all sorts of semantic meaning about the tokens, one dimension could represent “colour”, another “size”, another “rudeness”, and so on. The weights are using similarity to determine relevance.

当我们推导出 Q 和 K ,然后将它们相乘得到注意力权重时,我们完全基于标记之间的相关性进行操作。嵌入向量编码了标记的各种语义含义——一个维度可能代表“颜色”,另一个代表“大小”,再一个代表“粗鲁程度”,等等。权重利用相似性来确定相关性。

What WV allows the model to do is to then decide which dimensions to carry forward. In the sentence “Mary had a little”, what’s important about Mary is her name. The model could have also learned plenty about the drink Bloody Mary, or Mary Queen of Scots. These are irrelevant to the nursery rhyme, and it would introduce noise to carry them forward. So WV allows the model to filter out irrelevant features before mixing the embeddings together.

WV 使得模型能够决定将哪些维度传递到下一步。在“玛丽有只小羊羔”这句话中,关于玛丽重要的是她的名字。模型可能也学习了许多关于鸡尾酒“血腥玛丽”或苏格兰女王玛丽的信息。这些与童谣无关,将它们传递下去只会引入噪声。因此, WV 允许模型在将嵌入向量混合之前过滤掉不相关的特征。

Then we multiply that V by the weights we generated, and the output is a new set of embeddings:

然后我们将 V 乘以生成的 weights ,输出得到一组新的嵌入向量:

weights
1.000.000.000.00
0.610.390.000.00
0.460.230.310.00
0.380.250.270.10
×
V
-0.12-0.00-0.23
1.460.62-0.49
-0.83-0.04-0.01
0.970.180.78
=
output
-0.12-0.00-0.23
0.500.24-0.33
0.020.13-0.22
0.200.16-0.14

The final output of the attention mechanism is the last row of this output matrix. All of the contextual information from previous tokens has been mixed into this last row through the attention process, but all of the previous rows had to be calculated to do that.

注意力机制的最终输出是这个 output 矩阵的最后一行。通过注意力运算过程,之前所有标记的上下文信息都已融入这最后一行,但为了做到这一点,必须计算所有之前的行。

So all in all, embeddings go in and a new embedding comes out. The attention mechanism has done a lot of intricate math to mix tokens together in proportion to how important they are based on the WQ, WK, and WV matrices it learned during training. This is the mechanism that allows LLMs to know what’s important in its context window, and why.

总而言之,嵌入向量输入后,会得到一个新的嵌入向量输出。注意力机制通过大量精密的数学计算,根据训练过程中学习到的 WQ 、 WK 和 WV 矩阵所确定的重要性比例,将标记混合在一起。正是这种机制使得 LLMs 能够理解其上下文窗口中的重点内容及其原因。

We now, finally, know everything we need to know to talk about caching.

现在,我们终于掌握了讨论缓存所需的所有知识。

There is more to attention注意力机制不止于此

What I’ve shown here is a simplified (I know, right?) version of attention designed to highlight what matters most for prompt caching. There’s more to it in practice, and if you’re interested in going deeper I recommend the 3blue1brown video on attention.

这里展示的是注意力机制的简化版本(明白了吧?),旨在突出对提示缓存最重要的部分。实践中还有更多细节,如果您有兴趣深入了解,我推荐观看 3blue1brown 关于注意力机制的视频。

Prompt caching提示词缓存

Let’s take a look at the grid above again, but this time we’ll see it get populated as each new token is produced in the inference loop. Hit play to start the animation.

让我们再次看一下上面的网格,但这次我们将看到它随着推理循环中每个新令牌的产生而被填充。点击播放开始动画。

注意力权重
↘Maryhadalittlelambwhoseflee
Mary
had
a
little
lamb
whose
flee
每个 token 对应一行。

Every new token is appended to the input and reprocessed in full. But look closely, play the animation back a few times: none of previous weights change. The 2nd row is always 0.79 and 0.21. The 3rd row is always 0.81, 0.13, 0.06. We’re redoing lots of calculations we don’t need to. Most of the matrix multiplications for “Mary had a little” aren’t necessary if you’ve only just finished processing “Mary had a”, which is how the LLM inference loop works.

每个新生成的分词都会被追加至输入中,并完整地重新处理整个序列。但请仔细观察,反复回放动画演示:之前的权重参数其实从未改变。第二行始终是 0.79 与 0.21 ,第三行始终是 0.81 、 0.13 、 0.06 。我们正在重复大量非必要的计算。若 LLM 推理循环刚处理完”玛丽有只”,那么针对”玛丽有只小”的大部分矩阵乘法运算其实都是多余的——这正是 LLM 推理机制的实际运作方式。

You can avoid these duplicate calculations by making two changes to the inference loop:

要避免这些重复计算,只需对推理循环进行两处调整:

Let’s walk through the matrix multiplications again but this time, we have the first 4 tokens’ K and V matrices cached, and we only pass in a single token’s embeddings. Yes, it’s more matrix math, I’m sorry, but it’s mostly the same as above and we’re going to speed through it.

让我们再次演练矩阵乘法运算。但这次,我们已经缓存了前四个标记的 K 和 V 矩阵,并且只输入单个标记的嵌入向量。是的,这涉及更多矩阵运算,但大部分与前述过程相同,我们将快速过一遍。

Calculating a new Q produces just a single row as output. WQ hasn’t changed from before.

计算新的 Q 仅产生单行输出结果。 WQ 与先前版本保持一致。

embeddings
0.20-0.100.70
×
WQ
-0.740.91-0.21
-0.510.430.18
-0.56-0.210.76
=
Q(new)
-0.49-0.010.48

Then calculating a new K produces just a single row as output as well, and likewise WK is the same.

然后计算新的 K 也会只产生一行输出,同样 WK 也是如此。

embeddings
0.20-0.100.70
×
WK
0.13-0.51-0.63
-0.790.54-0.04
0.33-0.10-0.87
=
K(new)
0.34-0.23-0.74

But then we take that new row and append it to the 4 cached K rows from the previous iteration:

但接着我们将这个新行附加到之前迭代中缓存的 4 行 K 数据上:

cached K
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
append
K(new)
0.34-0.23-0.74
=
K
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
0.34-0.23-0.74

So now we have the K matrix for all of the tokens in the prompt, but we’ve only had to calculate the last row of it.

至此我们已获得提示中所有 token 的 K 矩阵,但仅需计算其最后一行。

We carry on in this fashion to get new scores:

我们继续这种操作模式来获取新的 scores :

Q(new)
-0.49-0.010.48
×
transpose(K)
-0.210.30-0.390.960.34
0.13-0.680.36-0.74-0.23
0.29-0.03-0.56-1.15-0.74
=
scores(new)
0.24-0.16-0.08-1.01-0.52

And new weights:

以及新的 weights:

softmax(
scores(new)
0.24-0.16-0.08-1.01-0.52
) =
weights(new)
0.320.210.230.090.15

The whole time, we only calculate what we need. No recalculation of old values at all. This continues with getting the new row of V:

在整个过程中,我们只计算所需部分。完全无需重新计算旧值。获取新行 V 的过程也是如此:

embeddings
0.20-0.100.70
×
WV
-0.740.91-0.21
-0.510.430.18
-0.56-0.210.76
=
V(new)
-0.49-0.010.48

And appending it to the V we had cached:

并将其附加到我们已缓存的 V 中:

cached V
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
append
V(new)
-0.49-0.010.48
=
V
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
-0.49-0.010.48

And finally multiplying the new weights with the new V to get the final new embeddings:

最后,将新的 weights 与新的 V 相乘,得到最终新的 embeddings :

weights(new)
0.320.210.230.090.15
×
V
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
-0.49-0.010.48
=
embeddings(new)
-0.08-0.09-0.08

This single new row of embeddings is all that we needed. All of the contextual information from previous tokens has been baked into it thanks to the cached K and V.

我们所需要的正是这个新嵌入行。由于使用了缓存的 K 和 V ,之前所有标记的上下文信息都已融合其中。

The data that gets cached is the result of embeddings * WK and embeddings * WV, so K and V. As a result, prompt caching tends to be called “KV caching.”

被缓存的数据是 embeddings * WK 和 embeddings * WV 的结果,即 K 和 V 。因此,提示缓存通常被称为”KV 缓存”。

Cache
K
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
0.34-0.23-0.74
V
-0.210.130.29
0.30-0.68-0.03
-0.390.36-0.56
0.96-0.74-1.15
-0.49-0.010.48

That’s it, those K and V matrices above, they are the 1s and 0s that the providers save in their giant datacenters to offer us 10x cheaper tokens, and much faster responses.

就是这样,那些上面的 K 和 V 矩阵,就是服务商储存在其巨型数据中心里的 1 和 0,用来为我们提供成本降低 10 倍的令牌和快得多的响应速度。

Providers hold on to these matrices for each prompt for 5-10 minutes after the request is made, and if you send a new request that starts with the same prompt, they reuse the cached K and V rather than recalculating them. What’s really cool is that you can partially match a cache entry and still use the bit that matched, not the whole thing.

服务商会为每个提示词请求保留这些矩阵 5 到 10 分钟,如果你发送的新请求以相同的提示词开头,他们会直接复用缓存的 K 和 V 矩阵,而不是重新计算。最酷的是,即使只是部分匹配缓存条目,你仍然可以使用匹配的部分,而不必完全匹配整个条目。

The visual below round robins between a few prompts that have similar prefixes, to show how cache entries might get used. Every so often the cache gets emptied to show how it fills back up.

下面的图示在几个具有相似前缀的提示词之间循环展示,以说明缓存条目可能被如何使用的情况。每隔一段时间,缓存会被清空,以展示它是如何重新填充的。

What is your perfect Sunday?
缓存为空。
缓存

    OpenAI and Anthropic do caching very differently from each other. OpenAI do it all automatically for you, attempting to route requests to cached entries when possible. In my experiments, by sending a request and then immediately resending it, I was able to get a hit rate of about 50%. Given how long the time-to-first-byte can get for long context windows, this could lead to inconsistent performance.

    OpenAI 和 Anthropic 在缓存机制上采用了截然不同的策略。OpenAI 会为用户自动处理所有缓存,尽可能将请求路由至已缓存条目。在我的测试中,通过发送请求后立即重发相同请求,缓存命中率大约能达到 50%。考虑到长上下文窗口下首字节到达时间可能非常漫长,这可能导致性能表现不稳定。

    Anthropic give you more control, letting you decide when to cache and for how long. You pay for this privilege, but in my experiments Anthropic route you to cached entries 100% of the time when you ask them to cache a prompt. This might make them a more appropriate choice for applications where you’re operating on long context windows and need predictable latency.

    Anthropic 则赋予用户更多控制权,允许用户自行决定何时缓存及缓存时长。虽然这项特权需要付费,但根据我的测试,当用户要求对提示词进行缓存时,Anthropic 能够实现 100%的缓存条目路由。对于需要处理长上下文窗口且要求可预测延迟的应用场景,这或许使 Anthropic 成为更合适的选择。

    Wait, what about temperature?那 temperature 参数呢?

    There are a variety of parameters that LLM providers offer you to control the randomness of what a model will produce. Common ones are temperature, top_p, and top_k. These parameters all affect the final step of the inference loop, where the model picks a token based on the probabilities it has assigned to each token in its vocabulary. This happens after the attention mechanism has produced the final embeddings, so prompt caching is unaffected by these parameters. You can change them freely without worrying about invalidating your cached prompts.

    LLM 提供商提供多种参数来控制模型生成内容的随机性。常见的参数包括 temperature 、 top_p 和 top_k 。这些参数都会影响推理循环的最后一步——即模型根据其分配给词汇表中每个词符的概率来选取词符。这一步骤发生在注意力机制生成最终嵌入向量之后,因此提示词缓存不受这些参数影响。您可以自由调整这些参数,无需担心会使已缓存的提示词失效。

    Conclusion结语

    I had a blast learning everything I’ve presented in this post. LLMs are fascinating technology and I think, as an industry, we’ve only scratched the surface of what they can do.

    我对本文所呈现的所有内容进行了深入学习,这过程充满乐趣。LLMs 是一项引人入胜的技术,我认为作为整个行业,我们对其潜能的探索才刚刚起步。

    ngrok.ai
    ngrok.ai
    ngrok.ai

    If you made it this far, you are the perfect customer for ngrok.ai. Route, secure, and manage traffic to any LLM (cloud or local) with one unified platform, now at its new home: app.ngrok.ai. New accounts get $1 in credit to make their first requests. Learn more in The new ngrok.ai or jump straight into the documentation.

    如果你一路读到了这里,你就是 ngrok.ai 的理想用户。它可以通过一个统一平台为任意云端或本地大语言模型路由流量、保护流量并管理流量。平台的新地址是 app.ngrok.ai。新账户可获得 1 美元额度,用来发送最初几次请求。详情见新版 ngrok.ai 的公告,也可以直接阅读文档。

    Acknowledgments致谢

    I devoured many resources to learn everything I needed to know to write this post, and here are the ones that I found most helpful:

    为了撰写这篇文章,我仔细研读了大量资料来掌握所需知识,以下是我发现最有帮助的资源:

    If you enjoyed this post, you will definitely enjoy them.

    如果您喜欢这篇文章,您一定会喜欢这些内容。

    Frequently asked questions常见问题

    What is prompt caching?什么是提示词缓存?

    Prompt caching is an LLM API feature where the provider reuses work the model already did on the start of a prompt. When a new request begins with the same tokens as a recent one, the provider skips recomputing that prefix, so those input tokens cost less and the first output token arrives sooner.

    提示词缓存是 LLM API 的一项功能。服务商可以复用模型先前处理提示词开头时做过的计算。如果新请求与最近的一次请求以相同的 token 开头,服务商便可跳过这段前缀的重复计算,从而降低输入费用,也让第一个输出 token 更快到达。

    What exactly gets cached in prompt caching?提示词缓存究竟保存什么?

    The K (key) and V (value) matrices produced by the attention mechanism for each token in a prompt. This is why prompt caching is often called “KV caching.” Providers store these matrices for a few minutes after a request, and reuse them for any new request that starts with the same token prefix, instead of recalculating them from scratch.

    缓存保存的是注意力机制为提示词中的每个 token 生成的 K(键)矩阵和 V(值)矩阵,因此提示词缓存也常叫作 KV 缓存。一次请求结束后,服务商会将这些矩阵保留几分钟。如果新请求以相同的 token 前缀开头,就可以直接复用这些矩阵。

    How much cheaper are cached tokens?缓存的 token 能便宜多少?

    As of this writing, cached input tokens cost 10x less than regular input tokens on both OpenAI and Anthropic’s APIs.

    在作者撰写本文时,OpenAI 和 Anthropic 的 API 对缓存输入 token 的收费都是常规输入 token 的十分之一。

    How long do prompt caches last?提示词缓存会保留多久?

    Providers typically hold cached K and V matrices for 5-10 minutes after a request. You can still get a partial cache hit if only the beginning of your prompt matches a cached entry.

    服务商通常会在请求结束后保留 K 和 V 矩阵 5 到 10 分钟。即使只有提示词开头的一部分与缓存条目匹配,也能部分命中。

    Is prompt caching automatic, or do I need to set it up?提示词缓存会自动启用,还是需要设置?

    It depends on the provider. OpenAI caches automatically and attempts to route matching requests to a cached entry. Anthropic requires you to explicitly mark what to cache and for how long, giving you more control over cache hit rates.

    这取决于服务商。OpenAI 会自动缓存,并尝试将匹配的请求路由到已有缓存。Anthropic 则要求你明确标记要缓存什么、缓存多久,因此你对缓存命中率有更多控制。


    Edit page
    Share this post:

    Comments


    Previous Post
    How to Scale a System from 0 to 10 million+ Users|如何将系统从零扩展到一千万乃至更多用户