Skip to Content
AxiomsAxioms
  • Article
  • Open Access

22 April 2026

15 Pages

Multi-Context Concatenation Across Requests for LLMs

,
,
,
,
and
1
School of Computer Science and Technology, Harbin Institute of Technology, Harbin 150001, China
2
Huawei Technologies Co., Ltd. Beijing Research Institute, Huawei Beijing Research Institute Building, Beijing 100095, China
3
School of Computer Science and Technology, Harbin Institute of Technology, Weihai 264209, China
4
School of Computer Science and Technology, Beijing Institute of Technology, Beijing 100081, China
This article belongs to the Section Mathematical Analysis

Abstract

Reusing separate, pre-filled Key-Value (KV) Caches for multiple contexts has become a common practice in handling multi-context scenarios with Large Language Models. However, this leads to a lack of cross-attention mechanisms between contexts. To address this, we propose CatLLM, the first method that concatenates multiple contexts across requests offline to compensate for this deficiency. Specifically, during offline processing, CatLLM identifies contexts that severely lack cross-attention by incorporating the weighted inner products of Q and K vectors from tokens in an un-concatenated context into an equivalently transformed weighted formulation for concatenated Q and K inner products. This yields a weighting w i A + B corresponding to the output vector difference, which can then be used to identify contexts with severe cross-attention deficiencies and concatenate them into a single context for KV Cache computation. Experimental results show that, compared to the baseline of separate caching (i.e., no concatenation), fully concatenating all contexts improves the F1 score by 6%. Meanwhile, the proposed method reduces the number of contexts requiring caching from 10 to 7 while achieving a 3% F1 score, thereby maximizing performance improvement while minimizing the degree of context compression.

1. Introduction

Large Language Models (LLMs) [1,2,3] demonstrate remarkable performance in foundational tasks such as text generation and code writing. However, as tasks grow increasingly complex, Retrieval-Augmented Generation (RAG) [4,5] systems frequently rely on substantial volumes of fixed system prompts, instructions, or in-context examples to achieve effective few-shot learning. A significant portion of this pre-loaded, tokenized information is repeated across multiple queries and inference sessions. Consequently, the efficient reuse of such repetitive content emerges as a critical challenge for enhancing the overall service efficiency and scalability of LLM-powered systems.
In current LLMs, the attention mechanism [6,7] operates based on the principle of Query-Key-Value (QKV) computation. Each token i is first converted from a word to a vector representation, denoted as x i . This vector is then mapped to query, key, and value vectors through linear transformations:
Q i = W Q x i , K i = W K x i , V i = W V x i ,
where W Q , W K , and W V are weight matrices. Essentially, these transformations are function mappings that project the original vector x i into different vector spaces [8,9]. The product of query and key, Q i · K j [10], represents a form of non-linear self-fusion of the vector itself, capturing the interaction between tokens i and j [11,12]. The softmax function then concretizes this fusion result into a probability distribution, where the sum of probabilities over all tokens equals 1.
Specifically, for token i, the attention scores with respect to all tokens j are computed as: s i j = Q i · K j and the softmax [13,14,15] over these scores yields:
α i j = softmax ( s i j ) = e s i j ∑ k e s i k .
The output for token i is then the weighted sum of value vectors:
o i = ∑ j α i j V j .
This output o i serves as the input to the next layer in the LLM. It is important to note that LLMs employ a mask mechanism to prevent attending to future tokens. Specifically, the Q K product for certain token positions is artificially set to an infinitesimally small value (e.g., − ∞ ) before the softmax computation [16]. This ensures that when exponentiated, these values approach zero, and after applying softmax, the corresponding probabilities also tend to zero.
Based on the aforementioned O ( N 2 ) complexity, caching the Key and Value (KV) [17] of contexts has become a crucial strategy to address the efficiency issues in large model serving [18]. Existing methods typically perform prefill operations for multiple contexts separately to enable KV Cache reuse across requests. However, this approach inherently lacks cross-attention interactions between different contexts [19]. For example, the upper part of Figure 1 illustrates the process of computing KV Caches for two separate contexts, while the lower part shows the process of concatenating these two contexts into a longer one. In Figure 1, the purple lines indicate that, due to the mask mechanism, subsequent tokens rely on the previously computed KV Cache to obtain the output of the current layer, which also serves as the input to the next layer. The red lines highlight the differences in attention computation before and after concatenation. Here, we focus specifically on the attention computation for the first token of the second context, while the connections for other tokens are only vaguely indicated. As can be seen from the figure, for layers 1 and 2, the red lines intuitively represent the influence of attention from the original first context. However, a similar phenomenon exists between every pair of adjacent layers, causing the differences observed in layer 1 to be further amplified in the following layers. This means that the cross-attention between documents before and after concatenation gradually intensifies as the layers go deeper.
Figure 1. The difference in computing cross-attention with and without concatenation (the red lines indicate the source of the difference).
To mitigate this limitation, current research [20,21,22] primarily focuses on recomputing the KV states of certain important tokens, aiming to compensate for missing attention at critical positions. While this method alleviates the issue to some extent, it still faces a significant drawback: when the content of one context changes—such as the first context—the KV Cache of all subsequent contexts must still be recomputed [23]. This substantially increases the overhead of cache reuse and constrains further improvements in the overall service efficiency of LLMs.
In fact, when LLMs process different requests, certain pieces of contextual information are often retrieved together or eliminated together from the candidate set. This “same-in-same-out” property of contexts allows them to be concatenated into a continuous contextual unit. Such concatenation does not affect cross-request serving yet significantly mitigates the missing cross-attention problem caused by traditional separate prefill. However, concatenating all contexts into a single whole loses the ability to reuse KV Cache across requests, whereas insufficient concatenation provides limited mitigation for the missing cross-attention problem. To address this, we propose CatLLM, a multi-context concatenation strategy designed for cross-request scenarios. Directly concatenating contexts [24,25] can most effectively mitigate the absence of cross-attention.
Specifically, the objective of CatLLM is to maximize the compensation for missing cross-attention with minimal context concatenation. Therefore, we first need to identify the contexts that require concatenation the most, i.e., the contexts where the absence of cross-attention is most severe. To this end, when multiple contexts are provided, we analyze the missing cross-attention for both scenarios—concatenating two contexts or not concatenating them—and further discuss the difference between the two cases. Unlike using the original attention formula [26,27,28], we extend it to compute the outputs for both cases and calculate the difference between them. In this process, we find that whether two contexts are concatenated is influenced by a softmax-like weighting factor. Thus, by reducing the value of this weighting factor, we can mitigate the impact caused by missing cross-attention. Extending this idea further, by selecting contexts for concatenation based on this weight, we can obtain the most reasonable context concatenation strategy.
Our contributions are primarily as follows:
  • We propose the first solution for concatenating multiple contexts across requests in LLMs, providing an important reference for question-answering tasks.
  • Our concatenation scheme fundamentally mitigates the lack of cross-context attention caused by prefilling multiple contexts separately.
  • Experiments show that our method effectively improves inference performance while enabling the reuse of multi-context KV Cache across requests.
In the subsequent sections of this paper, Section 2 provides a detailed derivation of the concatenation principle for CatLLM and proposes a greedy algorithm logic for multiple concatenations. Section 3 describes the experimental setup for CatLLM, while Section 4 presents the experimental results along with corresponding analysis and discussion. Finally, Section 5 concludes the paper by summarizing the contributions of the concatenation strategy and offering prospects for future research.

2. Our Proposed CatLLM

In LLM inference where KV Cache is prefilled based on multiple contexts separately, there is a lack of cross-attention mechanisms among different Caches. Compared to recalculating some tokens in real-time based on the required contexts when a request arrives, directly concatenating contexts for prefilling can effectively avoid attention deficiency. However, if all contexts are concatenated and prefilled at once, the ability to reuse across requests will be lost. To address this, this paper proposes the CatLLM method, which maximizes the mitigation of cross-attention deficiency by prefilling a small number of concatenated contexts while preserving cross-request reuse capabilities.

2.1. Derivation of Equations

To simplify the scenario, we focus only on two contexts here: context A and context B (lengths of n A and n B , respectively). In the case of multiple contexts, their KV Caches are denoted as K V A and K V B , respectively. The KV Cache for the concatenated context is referred to as the K V A + B . This section primarily discusses the impact on the output (o) of the first layer for context B under these two conditions.
According to the original formulation of attention, it can be deduced that for token i in context B at layer 1, only the KV within context B itself needs to be considered in the multiple contexts, denoted as o i B :
o i B = ∑ j = 1 i e Q i B K j B / d V j B ∑ j = 1 i e Q i B K j B / d .
Here, d denotes the dimension of Q K V . Similarly, the representation of token i in the concatenated context is computed. At this point, token i needs to consider the KV from both context A and context B, denoted as o i A + B :
o i A + B = ∑ j = 1 n A e Q i B K j A / d V j A + ∑ j = 1 i e Q i B K j B / d V j B ∑ j = 1 n A e Q i B K j A / d + ∑ j = 1 i e Q i B K j B / d .
By comprehensively observing the blue parts of Equations (4) and (5), we can roughly see that their forms are completely identical. The following will prove that they are also numerically identical: although the position of token i in Equation (4) is i, while in Equation (5) it becomes n A + i , the blue parts both represent the computation of i within context B. Therefore, the relative position between token i and other tokens in context B remains unchanged. Since RoPE’s positional encoding [29] has the property that the inner product of Q and K remains unchanged when the relative position is constant, although Q i B and K j B have changed, their inner product Q i B K j B remains unchanged, and thus they are also numerically identical. By substituting Equation (4) into Equation (5) and rearranging, we obtain:
o i A + B − o i B = ∑ j = 1 n A e Q i B K j A / d ( V j A − o i A + B ) ∑ j = 1 i e Q i B K j B / d .
As can be seen from Equation (6), this structure resembles the result of a softmax similar to attention weights multiplied by the Value (V). If we aim to reduce the missing cross-attention between contexts to zero without recomputing tokens—that is, make o i A + B − o i B approach zero, the most straightforward approach is to decrease the weight w i A + B :
w i A + B = ∑ j = 1 n A e Q i B K j A / d ∑ j = 1 i e Q i B K j B / d .
It should be noted that in Equation (7), the position of Q i B in the numerator is n A + i , while in the denominator, the position of Q i B is i. These two are not the same, and positional encoding should be assigned accordingly based on this requirement.
From Equation (7), it can be seen that the goal is for w i A + B to be 0, which represents a traditional sparsity structure. However, since traditional sparsity is only suitable for analyzing the importance of the KV itself to sparsify attention, and is not applicable to multi-context concatenation tasks, we extend the original attention mechanism accordingly.

2.2. Interpretation of Equations

Through the analysis of Equation (7), the influencing factors of w i A + B can be decomposed as follows:
  • n A : If context B and K j A remain unchanged, when n A increases, the denominator of w i A + B remains constant while the numerator increases, leading to a larger value. This indicates that when K V A is placed directly before K V B , the longer context A is, the greater its impact on the cross-attention deficiency of B.
  • i: If context A and Q i B remain unchanged, a smaller position index i results in an unchanged numerator for w i A + B and fewer accumulated terms in the denominator, leading to a larger value. This means that when K V A is placed before K V B , the effect is most significant for earlier tokens (e.g., the first token) in context B and weakest for later tokens (e.g., the last token).
  • K j A : If context B and n A remain unchanged, and the token j in context A has a stronger correlation with Q i B (i.e., a larger inner product), then the numerator of w i A + B increases while the denominator stays the same, thus w i A + B increases accordingly.
  • K j B : If context A and Q i B remain unchanged, and the token j in context B has a stronger correlation with Q i B (i.e., a larger inner product), then the numerator of w i A + B stays the same while the denominator increases, thus w i A + B decreases accordingly.
  • Q i B : If n A , K j A , and K j B all remain unchanged, the effect of changes in Q i B on w i A + B is difficult to judge intuitively.
In fact, the magnitude of w i A + B is jointly influenced by multiple factors, making it difficult to effectively control its value through direct adjustment of a single factor. Therefore, it is necessary to conduct further analysis of w i A + B in order to more clearly reveal its inherent characteristics.
To clearly express the overall influence of context A on B and avoid confusion with the notation for the combined tokens A+B, we define w A → B as the aggregated influence weight of all tokens in A on all tokens in B:
w A → B = 1 n B ∑ i n B w i A + B .
By substituting different contexts for A and B in the equation, we obtain Figure 2a, which illustrates the w A → B values corresponding to all attention heads across various contexts. It can be observed from the figure that w 5 → B for context 5 is generally large across most attention heads, whereas the values for context 10 are mostly small. This size pattern is consistent across different attention heads—either generally high or generally low. To simplify the representation and better observe the overall trend, we average the values across all attention heads and reduce them to a single representation. The result is shown in Figure 2b (top).
Figure 2. w A → B of the Llama-3.1-8B-Instruct model across 10 contexts on the 2WikiMQA sample: (a) per-head w A → B ; (b) top: average w A → B over all heads, bottom: column-wise mean as average aggregation weight w · → B .
Combining Figure 2b (top) and Equation (8), it can be observed that the value of w 5 → 10 is the largest, indicating that whether context 5 is concatenated before context 10 has the most significant impact on the absence of its cross-attention. Further examination of Figure 2b as a whole reveals that context 5 has a relatively significant influence on all other contexts, while the influence of other contexts on context 5 is comparatively smaller. This suggests that the impact reflects more of the intrinsic characteristics of the context itself. Therefore, we simplify Figure 2b (bottom) by computing the mean of each column, obtaining the average influence degree of any other context on context B, denoted as w · → B , as shown in Figure 2b (bottom):
w · → B = 1 | C o n t e x t s | ∑ A C o n t e x t s w A → B .
Here, C o n t e x t s denotes all contexts, and | C o n t e x t s | represents the total number of contexts, which also includes context B itself. In this case, when context B is concatenated before context B, the position encoding of the latter context B needs to be reset based on the premise that there is a preceding context B. This results in w B → B not being equal to 1 [16].
As can be seen from Figure 2b (bottom), the value of w · → 5 is the smallest, and the number of tokens in context 5 is the largest (1607); while the value of w · → 10 is the largest, and the number of tokens in context 10 is the smallest. Considering the relationship between w · → B and the corresponding token count | t o k e n s | in the remaining contexts, a negative correlation trend is observed between the two.

2.3. Concatenate Contexts

Prefilling multiple contexts separately leads to a lack of cross-attention between them. Therefore, concatenating a small portion of contexts not only allows reuse of KV Cache across requests, but also effectively mitigates the missing cross-attention. However, Figure 2a,b only present a single sample, which only indicate that w · → B is negatively correlated with | t o k e n s | . In fact, across all samples, w · → B does not strictly decrease monotonically with | t o k e n s | but shows a negative correlation trend. To derive a more rigorous concatenation strategy, we choose to follow the pattern shown in Figure 2b (bottom), i.e., concatenating the two contexts with the largest w · → B values.
In addition to determining which two contexts to splice, another key issue is the number of splices. We compare the effects of splicing from 1 to 5 times for two reasons: first, as the first systematic exploration of context splicing strategies, there is no established baseline for improvement; second, in real-world industrial scenarios, meeting diverse cross-request needs [30] and performance requirements involves flexible KV Cache pre-storage strategies without a one-size-fits-all solution. For example, the number of concatenations can be influenced by factors such as device requirements. In server applications, thanks to the strong performance of the server itself, it is assumed that it can simultaneously load the Top-1000 KV Cache. In this case, even if a small amount of erroneous information is concatenated into one of the contexts across other rounds of requests, the presence of 1000 contexts ensures that a few errors are not enough to dilute the vast amount of relevant information. Under such circumstances, multiple concatenations are recommended. However, for devices with limited computational performance, such as mobile phones, it is assumed that their performance can only support loading the Top-10 KV Cache. In this scenario, the insertion of irrelevant context can lead to overall information confusion, so the number of concatenations should be reduced. Therefore, the decision depends on the model’s performance and the practical conditions of the industrial environment. By enumerating various concatenation results, it becomes easier to select the appropriate number of concatenations.
In multiple concatenation rounds, adding short contexts increases their token count and reduces their weight w · → B , which may eventually remove them from having the lowest weight in later rounds and thus halt further concatenation. Consequently, candidate contexts vary dynamically across rounds. We employ a greedy strategy that selects the context with the smallest w · → B within the current context for concatenation in each round. The detailed procedure is outlined in Algorithm 1.
In Algorithm 1, Concatenate ( B 1 , B 2 ) denotes appending the text of B 1 to the front of the text of B 2 . The variable N u m specifies the minimum number of contexts to retain after concatenation, effectively setting a lower bound on the number of concatenated contexts. Meanwhile, we limit the concatenation process to at most K iterations to control its extent. These two variables are introduced to constrain the concatenation process because only a very small number of samples in the dataset deviate from having 10 contexts, resulting in an overall average of 9.93 contexts per sample—very close to 10. For the sake of readability, we uniformly denote the number of contexts as 10 throughout this paper. Although both K and N u m serve to constrain the concatenation process, K is primarily used to facilitate implementation, while N u m is designed to simplify the comparison and analysis of the resulting number of contexts. Thus, they serve different purposes.
Algorithm 1 Greedy Selection of Context for Concatenation
Require: 
Contexts to be concatenated C o n t e x t s = { C o n t e x t 1 , C o n t e x t 2 , ⋯ } N
Ensure: 
Concatenated contexts C o n t e x t s ′ = { C o n t e x t 1 ′ , C o n t e x t 2 ′ , ⋯ } N ′ ( N ′ < N )
  1:
k = 0
  2:
while  N > N u m   and  k < K   do
  3:
       k = k + 1
  4:
       w s · → B = ⌀
  5:
      for all  B ∈ C o n t e x t s  do
  6:
            compute w · → B
  7:
             w s · → B = w s · → B ∪ { w · → B }
  8:
      end for
  9:
      Identify B 1 , B 2 with the largest w · → B
10:
       C o n t e x t s = C o n t e x t s ∖ { B 1 , B 2 }
11:
       C o n t e x t ′ = Concatenate ( B 1 , B 2 )
12:
       C o n t e x t s = C o n t e x t s ∪ { C o n t e x t ′ }
13:
end while
14:
C o n t e x t s ′ = C o n t e x t s
Note that the concatenation between contexts can be completed offline, rather than in response to online requests, so it will not affect real-time responsiveness. To ensure the rigor of our approach, we also provide a theoretical derivation of the offline runtime for practical reference. In fact, the algorithm undergoes further optimization during implementation, and the optimized procedure differs slightly from Algorithm 1, as detailed below:
  • When some contexts are not concatenated, their weights do not need to be recomputed, thereby reducing a portion of the computation time. For example, in a given concatenation operation, if the algorithm concatenates contexts A and B, while contexts C and D remain un-concatenated, then w C → D does not need to be recomputed. Consequently, for the computation of w · → D , some weight values can be skipped.
  • In implementation, the numerator and denominator of w A → B are obtained by directly decomposing the softmax rather than by a second computation. The original softmax computation is already part of the regular inference within the model, so only the ratio of the decomposed terms needs to be calculated, incurring no additional weight computation complexity.
According to our calculations, the offline time consumption of this concatenation operation satisfies O ( min ( K , N − Num ) × L ) , where L denotes the total number of tokens for all contexts relevant to a given question. The length is linear because we only use the first layer, independent of the number of layers in the LLM. As for the specific numerical value of O ( L ) time consumption, it depends on the model type and device computation bandwidth. This time complexity is provided here for reference, to facilitate selection based on K, Num, and L. However, this time consumption occurs entirely before the user raises the question, and thus it is not perceived during the user’s questioning and response processes.

3. Experiments

Implementation. We use the original Huggingface [31] Transformers in PyTorch 2.1.0 [32], and extract the first layer of the model for independent computation to serve as the basis for concatenation.
Datasets. In this experiment, we select two commonly used question-answering datasets from LongBench [33]—2WikiMQA and HotpotQA—for evaluation. Each dataset contains 200 samples, with each sample consisting of a question, ten context passages, and one or more reference answers. It is worth noting that in these datasets, all ten context passages are essential for answering the corresponding question; none of them can be omitted. If only a subset of the context passages is used (e.g., extracting five of them for the experiment), any resulting performance degradation cannot be attributed solely to the absence of necessary information or the failure of the algorithm. Therefore, we are unable to experiment with subsets of context and must instead use the full set of context passages. Additionally, in the evaluation, we adopt the F1 score as the metric.
Models. We select the Qwen [34,35,36] and Llama [37] series models for evaluation, a decision motivated primarily by their widespread adoption and significant influence within the research community. This choice ensures that our findings are relevant to popular and commonly used architectures. In terms of model scale, we aim to balance representational capacity with practical hardware constraints. Consequently, we opt for the 3B and 8B parameter variants—specifically, the Qwen2.5-3B-Instruct (https://huggingface.co/Qwen/Qwen2.5-3B-Instruct, accessed on 10 August 2025) and Llama-3.1-8B-Instruct (https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct, accessed on 17 August 2025) models. This selection allows us to examine performance across different model sizes while remaining feasible under our computational resources.
Methods. To intuitively illustrate the impact of context concatenation (cat), we compare three methods: NoCat (no concatenation; prefill KV Cache separately then concatenate for inference; baseline), AllCat (full concatenation into a single context for inference), and CatLLM (concatenating context K times, with K ranging from 1 to 5). In real-world industrial settings, the value of K depends on practical requirements. Here it is used only for testing and demonstration. Figure 3 provides a visual comparison of these different approaches.
Figure 3. Schematic diagram of different text concatenation methods.
Environment. We conduct experiments on a server with a 64 GB 910B3 NPU, a 256-core Kunpeng 920 CPU (2.60 GHz, hyper-threading disabled), 2 TB DRAM, running EulerOS 2.0 (kernel 5.10.0).
Details. Experiments reveal that better results can be achieved by removing the position encoding from all KV Cache items, concatenating them, and then reassigning position encodings based on their respective locations. Therefore, this approach is applied to all methods in this paper, including the NoCat method where no context is concatenated—each KV Cache is concatenated and then reassigned position information.

4. Results and Discussion

Before quantitatively analyzing the F1 scores of specific models on the dataset, we first conduct a qualitative analysis of two extreme scenarios:
  • NoCat: No contexts are concatenated, which results in the maximum absence of cross-attention between contexts and should yield the poorest performance.
  • AllCat: All contexts are concatenated into a single context, ensuring no loss of cross-attention, which should lead to the best performance.
Given that CatLLM lies between these two extremes, its performance is expected to fall between them. For instance, compared to NoCat, CatLLM achieves better results but reduces the number of contexts. However, a decrease in the number of contexts may diminish its cross-request applicability.
While higher F1 scores and larger numbers of contexts are both desirable, they exhibit a negative correlation. To represent both aspects simultaneously with a single metric, we define Δ F 1 / Δ # (where # denotes the number of contexts):
Δ F 1 Δ # = F 1 Method − F 1 NoCat # NoCat − # Method .
From Equation (10), it can be observed that, on one hand, a larger numerator indicates a higher F1 score of the method, meaning better performance; on the other hand, a smaller denominator suggests that the amount of concatenated context is closer to NoCat scenario, implying stronger cross-request capability. Overall, a larger value of Δ F 1 / Δ # is desirable. It should be noted that Equation (10) is not a strictly derived evaluation formula and is only suitable for roughly analyzing the relative trade-off between F1 improvement and cross-request capability degradation from a qualitative perspective. To synthesize performance across multiple datasets, we compute the mean F1 score (Avg.) across all datasets and finally calculate Δ Avg . / Δ # . Therefore, a larger Δ Avg . / Δ # indicates a greater improvement in F1 but a smaller decrease in #, that is, a higher cost-effectiveness of a splicing method.

4.1. Overall Improvement

After experimentation, we present the effectiveness of NoCat and AllCat, along with the best-performing results from CatLLM, in Table 1. As shown in Table 1, compared to the NoCat method, CatLLM consistently improves the performance of different LLMs while only slightly reducing the number of contexts. Specifically, on the 2WikiMQA dataset, the F1 scores of both models increase by an average of approximately 5%, approaching the performance of AllCat, whereas on HotpotQA, the improvement is smaller, ranging from 0.7% to 0.9%. Despite the differences in model scale and architecture, both exhibit a consistent trend. This discrepancy may stem from the inherent characteristics of the datasets, making the method more suitable for 2WikiMQA. This paper focuses on the context concatenation mechanism and does not explore this aspect further.
Table 1. Comparison of the effects of different concatenation methods, where CatLLM demonstrates the best F1 score here. # represents the number of concatenated contexts.
A further analysis of Δ Avg . / Δ # reveals that although CatLLM does not perform as well as AllCat, the total number of concatenated contexts it produces is significantly larger than that of AllCat, thereby granting it stronger cross-request capability, which also leads to a greater Δ Avg . / Δ # . Since Δ Avg . / Δ # can only be used for qualitatively assessing the cost-effectiveness of a concatenation method rather than for quantitative comparison, we do not analyze the differences in specific numerical values here.

4.2. Detailed Experiments

In addition to comparisons with other methods, we conduct experiments with different numbers of splicing operations, ranging from 1 to 5 times, as shown in Table 2. From the table, it can be observed that as the number of splicing operations increases, the # gradually decreases, while the F1 score generally shows an upward trend. However, this increase is not strictly monotonic—the overall trend is upward, but occasional performance drops also occur. This indicates that some splicing operations do not effectively improve performance and may even have negative effects, a phenomenon observed in both models. This suggests that sacrificing certain cross-request capabilities does not necessarily lead to a corresponding improvement in performance. Of course, when such negative effects occur, their impact on the F1 score is relatively minor, approximately 1%. However, on the other hand, the negative impact on the reduction in the number of contexts is inevitable, inevitably leading to a decrease of 1 in the number of contexts, which directly affects the practicality of cross-request operations. This also highlights the necessity of using Δ Avg . / Δ # for qualitative comparisons.
Table 2. Comparison of the effects after concatenating different times in CatLLM. # represents the number of contexts after concatenation.
As shown in Table 2, as concatenation progresses, the number of contexts gradually decreases, and the overall F1 shows an upward trend, though not strictly monotonic. For example, Qwen achieves a better F1 when the number of contexts is 7 and performs well across both datasets, while in the Llama model, the best F1 is achieved when the number of contexts is 6. These observations indicate that a certain degree of concatenation benefits model performance. In practice, it can be observed that when contexts are concatenated 6 or 7 times, most contexts become relatively long and of similar length, resulting in a smaller variance in the number of | t o k e n s | . In this state, the influence among similarly long contexts is minimized. However, as concatenation continues, the length difference among contexts—which initially converged—increases again, widening the gap between the maximum and minimum values of w · → B and leading to a slight decline in performance. Due to the current limitation of 10 contexts, we set an upper limit of 5 concatenations. We hypothesize that if the initial number of contexts were unlimited, the lengths of contexts would repeatedly undergo cycles of convergence and divergence during iterative concatenation, and the F1 score would exhibit a spiral pattern of rising, gradually declining, and then rising again.
From Table 2, a simple conclusion applicable to real production environments can be drawn: appropriately concatenating contexts can not only effectively compensate for the lack of cross-attention between contexts and further enhance model performance; however, once the lengths of the contexts have become similar, further increasing the number of concatenations will enlarge the length differences among the contexts, which may lead to a slight decline in model effectiveness.

4.3. Online Process Analysis

Although CatLLM requires pairwise computations across multiple documents, which can be time-consuming, these computations are performed offline and do not affect online processing. Therefore, they introduce no additional latency. However, in similar multi-context scenarios, recomputation-based methods such as CacheBlend and EPIC operate by first caching the KV Cache and then, during online inference, loading the corresponding KV Cache based on the required context and performing necessary recomputation. This process inevitably introduces latency. In contrast, CatLLM performs its computations offline before the KV Cache is stored. As a result, these recomputation-based methods and CatLLM belong to different stages of KV Cache management. Theoretically, by using CatLLM to compute the KV Cache before storage and then leveraging CacheBlend and EPIC during runtime, the benefits of both approaches could be combined. However, since such integration is more of an engineering extension and adaptation rather than a focus of this paper, it will not be explored in detail here.
Additionally, since CatLLM operates entirely offline, there is no increase in GPU memory consumption or any change in throughput. This is because the total number of tokens in the KV Cache remains the same and unchanged. In summary, CatLLM behaves identically to NoCat or AllCat during the inference process.

4.4. Concatenation Basis and Layer Selection

In current LLMs, the shallower layers tend to focus more on syntactic processing, while the deeper layers emphasize semantic understanding. However, in this paper, we choose to utilize the first layer rather than deeper ones, and we provide an analysis and explanation for this choice.
First, we present a straightforward qualitative analysis: according to conventional reasoning, if there is a significant difference in the weights before and after concatenation at the shallow syntactic processing stage, this difference will only be amplified, rather than diminished, in deeper layers. This is because, as the layers go deeper, the lack of attention caused by not concatenating the preceding context becomes increasingly severe. Therefore, if the difference is already substantial in the first layer, it will continue to widen in subsequent layers, making deeper analysis unnecessary. This idea is somewhat similar to CacheBlend’s approach of computing attention differences only for the first layer. However, both the formulas used for computation and the application directions differ—CacheBlend is designed for recomputation, while CatLLM is intended for concatenation. These reasons explain our preference for selecting the first layer.
In fact, during the preliminary experiments of this paper with 3B and 8B models, we design experiments targeting different layers to verify the feasibility of this theory. The experimental results showed that, compared to other layers, selecting concatenation objects based on the first layer yields better concatenation outcomes. This finding aligns with the qualitative analysis mentioned above and ultimately led us to choose the first layer.

5. Conclusions

This paper proposes CatLLM, the first multi-context concatenation framework designed for cross-request scenarios. It systematically compensates for the missing cross-attention caused by independent pre-filling without recalculating the KV Cache. By deriving an upper bound for cross-attention weight differences, we demonstrate that offline concatenation of only a small number of “most influential” contexts can significantly enhance the model’s reasoning quality while incurring almost no loss in cross-request reuse capability. Experiments on 2WikiMQA and HotpotQA show that by sacrificing only 2–3 independent cache units, CatLLM improves the average F1 score of Qwen2.5-3B-Instruct and Llama-3.1-8B-Instruct by 3%.
More importantly, CatLLM provides a “plug-and-play” trade-off solution for industrial long-text services: it preserves the RAG system’s ability to flexibly reuse arbitrary combinations of multiple contexts while closely approximating the full attention upper bound with minimal concatenation. Future work will proceed in three directions: (i) extending the weight computation from the first layer to multiple layers for more precise “layer-head”-level concatenation; (ii) integrating dynamic sparsification techniques to further compress KV Cache memory usage after concatenation; and (iii) validating its generalizability across more long-context reasoning tasks and larger model scales and releasing a unified benchmark to promote ongoing community exploration of the “cross-request multi-context reasoning” paradigm.

Author Contributions

Conceptualization, Z.C., J.Z. and S.W.; methodology, Z.C.; validation, Z.C., H.X. and S.L.; formal analysis, Z.C. and S.L.; investigation, J.Z. and S.W.; resources, J.Z. and S.W.; data curation, S.L.; writing—original draft preparation, Z.C.; writing—review and editing, H.X., J.Z., S.W. and S.L.; visualization, Z.C.; supervision, B.L.; project administration, J.Z. and B.L.; funding acquisition, S.L. and B.L. All authors have read and agreed to the published version of the manuscript.

Funding

This research was funded by the National Natural Science Foundation of China, grant number 62176074; the National Natural Science Foundation of China, grant number 62406087; the Natural Science Foundation of Shandong Province, grant number ZR2024QF139; and the State Key Laboratory of Processors (ICT, CAS), grant number CLQ202406.

Data Availability Statement

The data presented in this study are openly available in THUDM/ LongBench at https://huggingface.co/datasets/zai-org/LongBench (accessed on 22 July 2025), reference number [33].

Conflicts of Interest

Authors Jingbin Zhang and Shuai Wang were employed by Huawei Technologies Co., Ltd. The remaining authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest.

References

  1. Vaswani, A.; Shazeer, N.; Parmar, N.; Uszkoreit, J.; Jones, L.; Gomez, A.N.; Kaiser, L.; Polosukhin, I. Attention is All you Need. In Proceedings of the Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, Long Beach, CA, USA, 4–9 December 2017; pp. 5998–6008. [Google Scholar]
  2. Devlin, J.; Chang, M.; Lee, K.; Toutanova, K. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2019, Minneapolis, MN, USA, 2–7 June 2019; Burstein, J., Doran, C., Solorio, T., Eds.; Association for Computational Linguistics: Stroudsburg, PA, USA, 2019; Volume 1, pp. 4171–4186. [Google Scholar] [CrossRef] [Scilit]
  3. Zhou, Z.; Ning, X.; Hong, K.; Fu, T.; Xu, J.; Li, S.; Lou, Y.; Wang, L.; Yuan, Z.; Li, X.; et al. A survey on efficient inference for large language models. arXiv 2024, arXiv:2404.14294. [Google Scholar] [CrossRef] [Scilit]
  4. Lewis, P.; Perez, E.; Piktus, A.; Petroni, F.; Karpukhin, V.; Goyal, N.; Küttler, H.; Lewis, M.; Yih, W.; Rocktäschel, T.; et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. In Proceedings of the Advances in Neural Information Processing Systems 33: Annual Conference on Neural Information Processing Systems 2020, NeurIPS 2020, Virtual, 6–12 December 2020. [Google Scholar]
  5. Li, X.; Cao, Y.; Ma, Y.; Sun, A. Long context vs. rag for llms: An evaluation and revisits. arXiv 2024, arXiv:2501.01880. [Google Scholar]
  6. Choromanski, K.; Likhosherstov, V.; Dohan, D.; Song, X.; Gane, A.; Sarlos, T.; Hawkins, P.; Davis, J.; Mohiuddin, A.; Kaiser, L.; et al. Rethinking attention with performers. arXiv 2020, arXiv:2009.14794. [Google Scholar]
  7. Edelman, B.L.; Goel, S.; Kakade, S.; Zhang, C. Inductive biases and variable creation in self-attention mechanisms. Proc. Mach. Learn. Res. 2022, 162, 5793–5831. [Google Scholar]
  8. Strang, G. Introduction to Linear Algebra; Wellesley-Cambridge Press: Wellesley, MA, USA, 2022. [Google Scholar]
  9. Horn, R.A.; Johnson, C.R. Matrix Analysis; Cambridge University Press: Cambridge, UK, 2012. [Google Scholar]
  10. Deza, M.M.; Deza, E. Encyclopedia of Distances; Springer: Berlin/Heidelberg, Germany, 2009; pp. 1–583. [Google Scholar]
  11. Herbrich, R. Learning Kernel Classifiers: Theory and Algorithms; MIT Press: Cambridge, MA, USA, 2001. [Google Scholar]
  12. Smola, A.J.; Schölkopf, B. Learning with Kernels; GMD-Forschungszentrum Informationstechnik Berlin: Berlin, Germany, 1998; Volume 4. [Google Scholar]
  13. Boyd, S.; Vandenberghe, L. Convex Optimization; Cambridge University Press: Cambridge, UK, 2004. [Google Scholar]
  14. Gao, B.; Pavel, L. On the properties of the softmax function with application in game theory and reinforcement learning. arXiv 2017, arXiv:1704.00805. [Google Scholar]
  15. Jaynes, E.T. Probability Theory: The Logic of Science; Cambridge University Press: Cambridge, UK, 2003. [Google Scholar]
  16. Brualdi, R.A.; Ryser, H.J. Combinatorial Matrix Theory; Springer: Berlin/Heidelberg, Germany, 1991; Volume 39. [Google Scholar]
  17. Pope, R.; Douglas, S.; Chowdhery, A.; Devlin, J.; Bradbury, J.; Heek, J.; Xiao, K.; Agrawal, S.; Dean, J. Efficiently Scaling Transformer Inference. In Proceedings of the Sixth Conference on Machine Learning and Systems, MLSys 2023, Miami, FL, USA, 4–8 June 2023. [Google Scholar]
  18. Ge, S.; Zhang, Y.; Liu, L.; Zhang, M.; Han, J.; Gao, J. Model tells you what to discard: Adaptive kv cache compression for llms. arXiv 2023, arXiv:2310.01801. [Google Scholar]
  19. Lei, Y.; Huang, R. Multi-document Summarization through Multi-document Event Relation Graph Reasoning in LLMs: A case study in Framing Bias Mitigation. arXiv 2025, arXiv:2506.12978. [Google Scholar]
  20. Hu, J.; Huang, W.; Wang, H.; Wang, W.; Hu, T.; Zhang, Q.; Feng, H.; Chen, X.; Shan, Y.; Xie, T. EPIC: Efficient Position-Independent Context Caching for Serving Large Language Models. arXiv 2024, arXiv:2410.15332. [Google Scholar] [CrossRef] [Scilit]
  21. Yao, J.; Li, H.; Liu, Y.; Ray, S.; Cheng, Y.; Zhang, Q.; Du, K.; Lu, S.; Jiang, J. CacheBlend: Fast Large Language Model Serving for RAG with Cached Knowledge Fusion. arXiv 2024, arXiv:2405.16444. [Google Scholar] [CrossRef] [Scilit]
  22. Cao, Z.; Si, Q.; Zhang, J.; Liu, B. Sparse Attention across Multiple-context KV Cache. arXiv 2025, arXiv:2508.11661. [Google Scholar] [CrossRef] [Scilit]
  23. Yang, H.; Zhang, R.; Huang, M.; Wang, W.; Tang, Y.; Li, Y.; Liu, Y.; Zhang, D. KVShare: An LLM Service System with Efficient and Effective Multi-Tenant KV Cache Reuse. arXiv 2025, arXiv:2503.16525. [Google Scholar]
  24. Cao, Z.; Liu, B.; Li, S. RPA: Reasoning Path Augmentation in Iterative Retrieving for Multi-Hop QA. In Proceedings of the AAAI Conference on Artificial Intelligence, Washington, DC, USA, 7–14 February 2023; Volume 37, pp. 12598–12606. [Google Scholar] [CrossRef] [Scilit]
  25. Cao, Z.; Xie, Y.; Liu, B.; Bu, K. Re3MHQA: Retrieve, Remove, and Return facts in multi-hop QA. Expert Syst. Appl. 2025, 281, 127566. [Google Scholar] [CrossRef] [Scilit]
  26. Li, Y.; Huang, Y.; Yang, B.; Venkitesh, B.; Locatelli, A.; Ye, H.; Cai, T.; Lewis, P.; Chen, D. SnapKV: LLM Knows What You are Looking for Before Generation. In Proceedings of the Advances in Neural Information Processing Systems 38: Annual Conference on Neural Information Processing Systems 2024, NeurIPS 2024, Vancouver, BC, Canada, 10–15 December 2024. [Google Scholar]
  27. Xiao, C.; Zhang, P.; Han, X.; Xiao, G.; Lin, Y.; Zhang, Z.; Liu, Z.; Sun, M. InfLLM: Training-Free Long-Context Extrapolation for LLMs with an Efficient Context Memory. In Proceedings of the Advances in Neural Information Processing Systems 38: Annual Conference on Neural Information Processing Systems 2024, NeurIPS 2024, Vancouver, BC, Canada, 10–15 December 2024. [Google Scholar]
  28. Hu, J.; Huang, W.; Wang, W.; Li, Z.; Hu, T.; Liu, Z.; Chen, X.; Xie, T.; Shan, Y. RaaS: Reasoning-Aware Attention Sparsity for Efficient LLM Reasoning. arXiv 2025, arXiv:2502.11147. [Google Scholar]
  29. Su, J.; Ahmed, M.; Lu, Y.; Pan, S.; Bo, W.; Liu, Y. RoFormer: Enhanced transformer with Rotary Position Embedding. Neurocomputing 2024, 568, 127063. [Google Scholar] [CrossRef] [Scilit]
  30. Akimura, A.; Nishi, H. Multi-context-aware cache accelerating processing on network processors for future internet traffic. In Proceedings of the 2010 the 12th International Conference on Advanced Communication Technology (ICACT), Gangwon-Do, Republic of Korea, 7–10 February 2010; Volume 1, pp. 377–382. [Google Scholar]
  31. Wolf, T.; Debut, L.; Sanh, V.; Chaumond, J.; Delangue, C.; Moi, A.; Cistac, P.; Rault, T.; Louf, R.; Funtowicz, M.; et al. Transformers: State-of-the-art natural language processing. In Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: System Demonstrations, Online, 16–20 November 2020; pp. 38–45. [Google Scholar]
  32. Paszke, A.; Gross, S.; Massa, F.; Lerer, A.; Bradbury, J.; Chanan, G.; Killeen, T.; Lin, Z.; Gimelshein, N.; Antiga, L.; et al. Pytorch: An imperative style, high-performance deep learning library. In Proceedings of the NIPS’19: 33rd International Conference on Neural Information Processing Systems, Vancouver, BC, Canada, 8–14 December 2019. [Google Scholar]
  33. Bai, Y.; Lv, X.; Zhang, J.; Lyu, H.; Tang, J.; Huang, Z.; Du, Z.; Liu, X.; Zeng, A.; Hou, L.; et al. LongBench: A Bilingual, Multitask Benchmark for Long Context Understanding. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), ACL 2024, Bangkok, Thailand, 11–16 August 2024; Ku, L., Martins, A., Srikumar, V., Eds.; Association for Computational Linguistics: Stroudsburg, PA, USA, 2024; pp. 3119–3137. [Google Scholar] [CrossRef] [Scilit]
  34. Bai, J.; Bai, S.; Chu, Y.; Cui, Z.; Dang, K.; Deng, X.; Fan, Y.; Ge, W.; Han, Y.; Huang, F.; et al. Qwen Technical Report. arXiv 2023, arXiv:2309.16609. [Google Scholar] [CrossRef] [Scilit]
  35. Yang, A.; Yang, B.; Hui, B.; Zheng, B.; Yu, B.; Zhou, C.; Li, C.; Li, C.; Liu, D.; Huang, F.; et al. Qwen2 technical report. arXiv 2024, arXiv:2407.10671. [Google Scholar]
  36. Yang, A.; Li, A.; Yang, B.; Zhang, B.; Hui, B.; Zheng, B.; Yu, B.; Gao, C.; Huang, C.; Lv, C.; et al. Qwen3 technical report. arXiv 2025, arXiv:2505.09388. [Google Scholar] [CrossRef] [Scilit]
  37. Touvron, H.; Lavril, T.; Izacard, G.; Martinet, X.; Lachaux, M.A.; Lacroix, T.; Rozière, B.; Goyal, N.; Hambro, E.; Azhar, F.; et al. Llama: Open and efficient foundation language models. arXiv 2023, arXiv:2302.13971. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.