KV Cache
"TLDR: This article introduces the importance of KV Cache in LLM (Large Language Model). It is a key step in accelerating operations to ensure that the inference speed is not affected when the input text grows during the conversation. The article explains the Self Attention mechanism and the concept of causal mask in detail, and discusses how KV Cache optimizes the prediction process by caching calculation results."
#KVCache
KV Cache is a very important step in accelerating operations in LLM. It can ensure that during the dialogue process of the model, the input text becomes longer and longer without affecting the inference speed.
As shown in the figure, during the LLM inference process, KV Cache occupies a large part of the video memory.

Attention mechanism
The essence of the LLM process is to input n tokens, output the n+1th token, and when the n+1th token is obtained, predict the n+2nd token based on 0~n+1 tokens, and repeat.
In predicting the next token in LLM, the most critical step is the calculation of Self Attention. Assume that we input N tokens and get N q, k, v vectors. The mathematical expression is
The process of Self Attention is to perform qkv calculation on N tokens. The specific formula is . After removing the fixed coefficient , we get
In this way, the attention vector of the th token is obtained as
Causal mask
In the process of predicting the th token, llm can only see tokens from to , but cannot see and subsequent tokens. The mathematical description is , pay attention to the range change of .
KV Cache
It can be noted that when calculating tokens, needs to be calculated for each , where is shared.
Secondly, when calculating tokens, it is necessary to calculate for each . appears again
Therefore, kv can be cached. When calculating tokens, you only need to calculate again.

It is easier to understand from a matrix perspective. As shown in the figure, the KV of all past Tokens is calculated, and the formula is . When calculating the next Token through the current Token, the formula is , so caching is enough
Why is there no Q Cache?
From the above derivation, we can know that predicting the next token does not need to be calculated with the Q vector of the previous token. It only needs to use the Q vector corresponding to the current token, so there is no need to cache