FragRel: Exploiting Fragment-level Relations in the External Memory of Large Language Models (2024)

Abstract: To process contexts with unlimited length using Large Language Models (LLMs), recent studies explore hierarchically managing the long text. Only several text fragments are taken from the external memory and passed into the temporary working memory, i.e., LLM’s context window. However, existing approaches isolatedly handle the text fragments without considering their structural connections, thereby suffering limited capability on texts with intensive inter-relations, e.g., coherent stories and code repositories. This work attempts to resolve this by exploiting the fragment-level relations in external memory. First, we formulate the fragment-level relations and present several instantiations for different text types. Next, we introduce a relation-aware fragment assessment criteria upon previous independent fragment assessment. Finally, we present the fragmentconnected Hierarchical Memory based LLM. We validate the benefits of involving these relations on long story understanding, repositorylevel code generation, and long-term chatting.

heading: 1 Introduction
text: The limited context window length constrains applications of Large Language Models (LLMs) in some practical scenarios, such as answering questions based on complete books or movie scripts (Kočiskỳ et al., 2018), writing codes within complete Github repositories (Zhang et al., 2023a), etc. To resolve this problem, some works (Ding et al., 2023; Han et al., 2023; Xiao et al., 2023) attempt to expand the context length of classical LLM inference framework via continual training or sparse attention mechanism. However, existing approaches are either limited to a finite expansion length (Packer et al., 2023; Schuurmans, 2023), or prone to performance degradation, especially when dealing with very long contexts (Liu et al., 2023).
Recent studies (Packer et al., 2023; Wang et al., 2023b; Ram et al., 2023) explore to hierarchically
process the long text. Each time only partial fragments of long text are retrieved from external memory and fed into LLM’s context window, a.k.a, temporary working memory, thereby eliminating the context length constraint and alleviating the inferior influence of substantial irrelevant content. However, current external memory managers simply split the complete long context into independent fragments, assessing their isolated importance during retrieval. This constrains the inference capability of Hierarchical Memory based LLMs, particularly in scenarios (e.g. understanding coherent story or code repository) where there are intensive associations across fragments of long text.
To address this issue, we propose to integrate these fragment-level relations into the external memory management by introducing a relationaware fragments assessment score during retrieval. First, we formulate the relations between two fragments as a real number, with higher values corresponding to stronger relation strength. The calculation of relation quantity could have different instantiations for different context types (e.g. narrative stories, code repositories, or historical dialog) and different relation types (e.g. semantic relations or structural relations). Next, based on the isolated relevance scores used in past external memory retrievers, we further calculate every fragment’s environmental relevance score, which is defined as a normalized relation-weighted summation of other fragments’ independent scores. During retrieval, the combination of independent score and environmental score is employed for assessing every fragment’s importance. An adjustable coefficient is introduced to control the influence of environmental score. Finally, in the same as previous works (Packer et al., 2023; Ram et al., 2023), we concatenate the retrieved content and the requested instruction as LLM inference input.
Extensive experiments validate the benefits of incorporating these fragment-level relations during
16348
retrieval. The experiments encompass a variety of base LLMs (Llama2 (Touvron et al., 2023), ChatGPT, ChatGLM (Du et al., 2022), etc. ), different temporary context lengths (1K, 4K, 8K, 20K, etc. ), and multiple long context scenarios (Long Story Understanding (Kočiskỳ et al., 2018), Repositorylevel Code Completion (Zhang et al., 2023a), and Long-term Chatting with Human (Lu et al., 2023)).

heading: 2 Related Work
text: Temporarily Long Context Processing. One line of works explores how to process long context under the typical LLM inference framework, in which the complete context is directly stored in the LLM context window (i.e. temporary memory). Among them, a series of works (Dai et al., 2019; Ding et al., 2023; Han et al., 2023; Xiao et al., 2023; Xiong et al., 2023) study extending the context length of Transformer-based models via efficient attention mechanism and recurrent inference strategic. In addition, some works (Li, 2023; Jiang et al., 2023a) investigate how to compress the length of long text content to mitigate the impact of excessive irrelevant text. Although the long text processing capability of the large language models can be enhanced by expanding the context window or compressing the context content, the context length that can be handled remains limited.
External Memory augmented LLMs. Another line of works introduce an additional external memory, forming a hierarchical memory based inference framework, thereby processing context of any length. In this framework, only partial content fragments are retrieved from external memory for knowledge updating (Wu et al., 2022; Wang et al., 2023b) or answering knowledge-intensive questions (Lewis et al., 2020; Guu et al., 2020;
Borgeaud et al., 2022; Lan et al., 2023; Wang et al., 2023a; Yang et al., 2024). The most popular retrieval method is first calculating the text embedding similarity for isolated fragments of external context using pre-trained embedding models (Su et al., 2022; Zhang et al., 2023b), and then retrieving the text fragments with higher similarity to the requested question or current temporary context.
Benefiting from the zero-shot generalization capability of LLMs, the retrieved fragments can be directly concatenated with instructions as model input (Ram et al., 2023), eliminating the need for additional training. This further facilitates more flexible external memory augmented LLM inference frameworks. Some studies explore the collaborative use of retrieval and generation (Gao et al., 2022; Yan et al., 2024), as well as further multi-round retrieval-generation interleaving framework (Trivedi et al., 2022; Jiang et al., 2023b; Asai et al., 2023; Shao et al., 2023; Feng et al., 2023). Saad-Falcon et al. (2023) utilizes explicit prompts about the structure of external context for enhanced retrieval. Additionally, MemGPT (Packer et al., 2023) automatically reads and writes the external memory, enabling more flexible external memory reasoning.

heading: 3 Methodology

heading: 3.1 Preliminary

heading: 3.1.1 Temporary Memory based LLM
text: Formulation. Traditional language models receive input x and generate the output y by:
y = LLM(x). (1)
The input x is straightly passed into the context window of LLM. Notably, the instructed LLMs (Ouyang et al., 2022) could take various
user instructions x and produce the corresponding responses y. Inspired by human cognition, the LLM context window could be viewed as the working memory which temporarily stores information (Packer et al., 2023; Li et al., 2022). For clarity, we refer to this traditional LLM reasoning framework shown in Equation. 1 as Temporary Memory based LLM (TempMem-LLM).
Long Text Processing. In many practical tasks, the input content includes not only user instructions x, but also an additional long context T , such as answering questions based on complete storybooks or movie scripts (Kočiskỳ et al., 2018), writing codes in long Github repository (Zhang et al., 2023a), and constructing agents capable of engaging in longterm conversations (Lu et al., 2023; Zhong et al., 2023). In these scenarios, TempMem-LLM simply concatenates and processes the long context T and instruction x in its working memory:
y = LLM(x⊕ T ), (2) where ⊕ represents the concatenation operation.
When the text length of T exceeds the context window limitations of LLM, we could cut its additional content of T for executing inference. In next section, we present another framework for effectively processing the lengthy context T via storing
it in external memory and retrieving relevant fragments for inference every time.

heading: 3.1.2 Hierarchical Memory based LLM
text: Unlike TempMem-LLM which handles all context in its temporary working memory, the Hierarchical Memory based LLM (HieraMem-LLM) integrates an additional non-parametric external memory for managing the long context T .
Formulation. Instead of directly being concatenated with the user instruction x, the context T is independently processed in HieraMem-LLM. Therefore, it consists of two decoupled modules, i.e., the external memory management module processing the long context T , as well as the LLM forward inference module containing the temporary working memory. Formally, we have:
T ret = Mem-MGR(x, T ), y = LLM(x⊕ T ret). (3)
Mem-MGR is the external memory manager, which takes the requested instruction x as input and returns relevant fragments from T .
External Memory Manager. The typical external memory manager consists of three steps, i.e.,
fragment splitting, independent score calculation, and fragment selection. 1. Fragment Splitting. It splits the long text T into N short fragments c∗. 2. Independent Score Calculation. It calculates the independent score sindi (or score ind i ) for every fragment ci based on user input x, i.e.,
sindi = Similarity(x, ci). (4)
The similarity function is often instantiated as the cosine similarity between embedding vectors of x and ci, which could be calculated using pretrained text embedding models, e.g. the Contriever model (Izacard et al., 2021). 3. Retrieved Context Picking. With fragment scores sindi , we select related fragments with top K scores and feed them into the temporary memory of LLM.
Although HieraMem-LLM effectively manages the long context T by utilizing external memory, the context is decomposed into unrelated segments, disrupting the structural integrity of the context.
TempMem vs. HieraMem. TempMem-LLM straightly handles the complete long text T in its working memory, integrating token-level correlations during inference. The simple concatenation approach in Equation 2 suffers the following issues: (1) When T exceeds the model’s context length constraint, the LLM is unable to do prediction. (2) The information irrelevant to instruction x can interfere with the model’s processing, leading to performance decline (Liu et al., 2023). (3) Reprocessing the lengthy context T each time consumes excessive computational resources. To address the issues of TempMem-LLM, HieraMemLLM incorporates the external memory to manage the prolix context T . Only a few related fragments are extracted for LLM inference.
However, existing external memory managers select fragments based on only isolated fragment content, overlooking intensive relations between fragments. While in TempMem-LLM, the longterm correlations could be employed via the attention mechanism over the complete text, enabling comprehensive context modeling.

heading: 3.2 Fragment Relations

heading: 3.2.1 Definition
text: We formulate the relations between every pair of fragments (ci, cj) as follows:
wi,j = Frel(ci, cj), 1 ≤ i, j ≤ N, (5)
where wi,j is a real numbers measuring the relation strength between fragment ci and fragment cj . The larger value of wi,j indicates the stronger correlation between ci and cj . Next, we present several specific implementations for Frel.

heading: 3.2.2 Fragment Relation Instantiations
text: This section introduces several instantiations of fragment-level relations and discusses the importance of considering these relations.
Semantic Relation. Semantic association is the most common type of connection between text segments. The semantic correlation between text fragments can be measured by the cosine similarity between the latent embeddings of fragments,
Frel(ci, cj) = 1− ei · ej
∥ei∥∥ej∥ , (6)
where ei and ej represent the latent embeddings of fragments ci and cj respectively. They could be obtained with the pre-trained embedding models, e.g. the Contriever model (Izacard et al., 2021).
Context Structure Relation. In consecutive books or long-term dialog, there are significant content correlations between the contiguous preceding and following fragments. The fragments with closer positions in the context have stronger relevance. This contextual relationship strength can be defined as:
Frel(ci, cj) = w|loci−locj |rel , wrel ∈ [0, 1], (7)
where loci refers the absolute position of fragment ci in the external context T . wrel can be adjusted to control the relation strength between fragments. When wrel = 0, it represents there is no relation between fragments, and our method degrades to previous fragment-independent external memory.
Code Structure Relation. Compared to natural language, code repository fragments have more complex interrelations. We construct the structure graph G for a complete code repository. The code graph G consists of all code parsing nodes (including function definition, function body, assignment expression, etc. ). The code parsing nodes are connected by edges based on the parsing tree, function calling relation, and the files directory structure. The edge weights take values in [0, 1] and are set based on the edge types. In section. A we present more details about the construction of the code
graph G. Based on the code graph G, we formulate the code structure relation as follows:
Frel(ci, cj) = ∑NGci k=1 ∑NGcj l=1 K ci,cj k,l · Dis(g ci k , g cj l )
∑NGci k=1 ∑NGcj l=1 K ci,cj k,l
,
K ci,cj k,l = len ci k · len cj l ,
(8) where NGci represents the number of nonoverlapping graph nodes in the i-th repository fragment, gcik is the k-th graph node in the i-th repository fragment, lencik represents the text length of the k-th paring node in fragment ci. Dis(g ci k , g cj k ) is the shortest path distance between node gcik and g cj k on the code graph G. Section. A shows more details on the calculation of Dis(gcik , g cj k ).
More Relations. More relations could be designed for specific text properties and practical needs. For example, we can gauge the correlation strength between academic papers based on citation relationships and author associations.
Importance of Fragments Relations. The fragments-level relations are significant for: 1. Ubiquitous existence. These fragments-level relations ubiquitously appear in a variety of long texts. For example, in narrative books or movie scripts, the storyline progresses coherently from beginning to end, with each fragment c∗ intricately connected to its preceding and following fragments c∗. In code repository, structural correlations exist among different code lines, and function calling or variable passing relationships exist between different code files and functions. Therefore, the content of different code fragments c∗ are densely related. 2. Assisting long text understanding. Unlike TempMem-LLM latently utilizes long-term relations, we posit that involving explicit inter-relations plays its role in external memory management by forming a more comprehensive assessment criteria for fragment selection. Specifically, when neglecting the fragments relations, the external memory retriever greedily supposes only the fragments with high direct similarity to the input x is helpful (Previous). The consideration of fragment relations allows a more comprehensive fragments assessment criteria: i.e. the fragments with both higher direct similarity and contextual similarity to x is important (Ours). The contextual similarity of fragment ci refers to the similarity between the ci’s related fragments and the input x. The new assessment criteria retrieve not only directly similar
fragments but also take account of: (a) fragments within a relevant environment, (b) contextual fragments of relevant fragments, which could help understand the directly relevant fragment, (c) indirectly relevant fragments.

heading: 3.3 Fragment-connected Memory Retrieval
text: This section introduces the integration of fragment relations by calculating the relation-aware assessment scores, and presents the overall framework of Fragment-connected HieraMem-LLM.

heading: 3.3.1 Relation-aware Fragment Assessment
text: Different from vanilla retriever which considers the independent importance of every fragment using independent score sindi , we instead propose to calculate a Relation-aware Score for more comprehensively considering the importance of every fragment.
Definition. For the i-th fragment, the relationaware score is composed of two parts: its independent score sindi and its environment score s env i . The independent score measures its direct relevance degree with question x, defined in Equation 4. The environment score senvi assesses its related fragments’ relevance with question x. We formulate senvi (or scoreenvi ) as the normalized weighted summation over independent scores senvj of related fragments:
senvi =
∑ j wi,j · sindj∑
j wi,j , (9)
where wi,j is the fragment relation defined in Equation 5. The normalization operation is introduced to ensure the consistent numerical scale of senvi with sindi .
Combining sindi and s env i , we define Relationaware Score sreli (or score rel i ) of the i-th fragment as follows:
sreli = s ind i + α · senvi , (10)
where α is an adjustable coefficient, employed to control the influence of environment score.
Relation Distance and Complexity. The utilization of explicit fragment-level relations shown in Equation. 9 is irrelevant with fragments distance, while TempMem-LLM extracts relations within ranges limited by the context window length. Additionally, some complex relations (e.g. code structure relations) are challenged to automatically learn while they could be employed explicitly.

heading: 3.3.2 Fragment-connected HieraMem-LLM
text: Based on the proposed relation-aware score, we introduce the overall framework of Fragmentconnected HieraMem-LLM, shown in Figure. 2.
We first split the long text T into fragments and acquire their independent scores. Next, considering the extracted relations, we calculate the relation-aware score sreli for every fragment using Equation 10. Based on these fragments along with relation-aware scores, we select relevant fragments as retrieved context:
T relret = cr1 ⊕ cr2 ⊕ ...⊕ crK , r1, r2, ..., rK = arg TopKi s rel i ,
(11)
where ⊕ represents operation of concatenating two text fragments, r∗ is the indexes of retrieved fragments. The final response is generated y with LLM as follows:
ŷ = LLM(x, T relret ). (12)

heading: 3.3.3 Discussion
text: This section provides an intuitive explanation of the influence of contextual similarity (or named environmental similarity score senvi ). 1. The fragments with high contextual similarity are mostly beneficial for LLM inference. Suppose fragment ci has a high contextual similarity senvi , which refers to that ci is situated around a "high score fragment" or within a "high score environment". The "high score fragment" is the fragment with a large direct similarity to the input x. The "high score environment" is a lot of related fragments with relatively large direct similarity to the input x. Therefore, the fragment ci with high contextual similarity could always help understand the "high score fragment" or "high score environment". 2. For LLMs, precisely understanding the "high score fragment" or "high score environment" is particularly important to generate correct results. The "high score fragment" or "high score environment" is the fragment with large direct similarity to the input x. If they contain beneficial information for LLM inference, the precise understanding enables LLMs to exploit this information. If they are useless for LLM inference, the precise understanding prevents LLMs from being disturbed by them. 3. Additionally, the fragments with high contextual similarity potentially contain important information for LLM inference, although they may not be directly similar to current input x. Some important information is not contained in the "high score
fragment" with large direct similarity to the input x, but situated in its surrounding fragments. These surrounding fragments could be retrieved through a high contextual similarity. This phenomenon is particularly prevalent in code repository fragments retrieval, where some important information (eg. function parameters, function return type) is contained in the indirectly relevant fragments containing the "function definition".
Therefore, the performance is enhanced through retrieving the fragments with both higher direct similarity and contextual similarity to the input x.

heading: 4 Experiment
text: We evaluate the proposed Fragment-connected HieraMem-LLM on three long text understanding tasks: long story understanding (Section. 4.1), repository-level code generation (Section. 4.2), and memory-enhanced chatting agent (Section. 4.3).

heading: 4.1 Long Story Understanding

heading: 4.1.1 Setup
text: Dataset. NarrativeQA (Kočiskỳ et al., 2018) is a challenging story comprehension benchmark, consisting of human-written question-answer paris based on long (average 18K words) story books or movie scrips. LLMs are required to understand the long-term relations in the lengthy stories to answer these questions. We employ the 200 extracted testing samples in LongBench (Bai et al., 2023).
Metrics. Following LongBench (Bai et al., 2023), we assess the generated response with the F1 Score, a widely used metric in question-answering tasks.
Baselines. We classify baselines into 2 categories: Temporary Memory based LLMs (TempMem LLMs) and Hierarchical Memory based LLMs (HieraMem LLMs). (a) TempMem-LLMs: We directly compare the results shown in LongBench (Bai et al., 2023), covering LLMs with extensive parameter amount and context length (including the context length expanded LLMs). When the input text exceeds LLM’s context length, the content in the middle position of the text is truncated. (b) HieraMem-LLMs: We experiment with different context limitations (1K, 2K, ..., 20K, 28K words), and different fragments lengths (500 and 800 words per fragment). The embeddings are calculated with Contriever (Izacard et al., 2021), a popular pre-trained model for text retrieval. The base LLMs includes Llama2-7B-4K (Touvron et al.,
2023), ChatGLM3-6B-32K (Du et al., 2022) and GPT-3.5-Turbo-16K.
Relation Integration Details. We calculate the fragment relations using semantic relation (Equation. 6) and context structure relation (Equation. 7), denoted as "A-FragRel" and "B-FragRel" respectively. Except for specific statements, we set wrel = 0.3 and α = 0.5.

heading: 4.1.2 Result
text: We present the experimental results in Figure. 3 and Figure. 4. The corresponding score value is reported in Table. 4 and Table. 5, respectively.
TempMem vs. HieraMem. According to Figure. 3, the Hierarchical Memory based LLMs (the columns) could outperform Temporary Memory based LLMs (the horizontal lines), especially on large context windows (more than 8K tokens). This is consistent with the conclusion that retrieval augmentation could help improve long context LLM in the previous work (Xu et al., 2023).
Benefits of Fragment-level Relations. As shown in Figure. 3, across all base LLMs and context length, the structural relation augmented HieraMem-LLMs (noted as B-FragRel-*) consistently outperforms the counterpart HieraMemLLMs (noted as No-FragRel-*). The performance enhancement is especially noticeable under enough long context length. This indicates that the integration of fragment-level relations effectively alleviates the deficiencies of HieraMem-LLM in terms of external memory management.
Semantic Relation vs. Structure Relation. Figure. 3 compares semantic relation ("A-FragRel-*") and context structure relation ("B-FragRel-*") on fragment length 500. The semantic relation offers a slight enhancement under enough long context, while the context structure relation provides consistent and significant improvement across various context lengths. We posit this is due to that the embedding based retrieval has implicitly considered the semantic association between segments.
Different Relation Parameters. Figure. 4 presents the performance with varied relation parameters wrel and α on different context lengths and fragment lengths. Although the optimal values of relations parameters (wrel and α) for different setups (including fragment length, context types, and context length constraint etc. ) are difficult to ascertain, most empirical values (α ∈ [0.2, 0.5], wrel ∈ [0.1, 0.7]) can lead to performance enhancement.

heading: 4.2 Repository-level Code Generation
text: Dataset. We conduct the code generation experiment on RepoEval (Zhang et al., 2023a), a benchmark constructed using the latest repositories source from GitHub. Specifically, two code completion tasks are considered: (a) Line Completion: completing random code lines, (b) Api Invocation Completion: completing random code lines that invoke in-repository apis. Both tasks contain 1600 test samples across 8 repositories.
Metrics. Following previous works (Zhang et al., 2023a; Lu et al., 2021, 2022), we evaluate the code generation performance using two metrics: Exact
Match (EM Score) and Edit Similarity (ES Score). EM score evaluates how many completions are exactly the same to real code. ES score represents the similarity score between the generated and real code lines.
Baselines. We employ Codellama-34b (Roziere et al., 2023) with 4K context length as the base LLMs, and the same prompt formats as RepoCoder (Zhang et al., 2023a). To extensively evaluate the integrated relations, we consider not only the single step Vanilla Retriever but also the iterative retrieval method RepoCoder (Zhang et al., 2023a). Noted that we report the result of oracle iterative retrieval, i.e. the upper bound of performance during the iterative retrieval procedure. Section. B.2 presents more implementation detail.
Relation Integration Details. In this experiment, we use the code structure relation shown in Equation. 8 , and we set relation weight α = 0.5.
Performance Comparison. Table 1, 2 present the results of the line completion task and api invocation completion task, respectively. On the two tasks, the integrated relation consistently improves the performance of both the single step retrieval inference framework and the iterative retrieval inference framework. This empirically demonstrates that fragment-level relations are greatly helpful in long code scenarios.

heading: 4.3 Memory-enhanced Chatbot
text: Dataset. We perform the long-term chatting experiment on MTBench+ (Lu et al., 2023). Every chatting stream consists of 12 ∼ 15 turns dialogs, covering topics such as "STEM exams", and "literary writing". At the end of every dialog, a challenging question is added by the experts. The questions could be classified into 3 categories: (a) "Retrospection" requires the model to respond content
mentioned previously, (b) "Continuation" requires the model to finish a further task about talked topics, (c) "Conjunction" requires answering questions involving multiple topics existing in the dialog. There are 54 test samples, 18 for every type.
Metrics. Following the origin benchmark (Lu et al., 2023), we assess the generated response using LLM-as-a-judge method (Zheng et al., 2023), where GPT4 is instructed to check the faithfulness of the model response and produces a 1 ∼ 100 integer score. We utilize exactly the same testing setup (including prompt format, GPT4 version, hyperparameters, etc. ) as (Lu et al., 2023).
Baselines. We consider the ChatGPT-based baselines reported in MemoChat (Lu et al., 2023), including various external memory enhanced frameworks (Zhong et al., 2023; Lee et al., 2023). In addition, we introduce a dense retrieval augmentation
baseline, named MemRetrieval-ChatGPT. Following previous work (Lu et al., 2023), we constraint the temporary context length as 2K tokens. Section. B.3 presents more implementation detail.
Relation Integration Details. Based on MemRetrieval-ChatGPT, we integrate the context structure relations defined in Equation. 7. We set wrel = 0.8 and α = 0.5 in our experiments.
Inference Expense Comparison. Approximately, MemoChat (Lu et al., 2023) consumes about 1M input tokens and 170K output tokens. MemRetrieval (+FragRel) costs about 680K input tokens and 65K output tokens. The introduced dense retrieval framework relatively reduces about 32% input tokens and 62% output tokens cost.
Performance Comparison. Table 3 presents the experimental results. Utilizing the same 2K temporary context length, the introduced MemRetrieval achieves comparable performance to MemoChat (Lu et al., 2023). Our fragment relations augmented methods consistently outperform all baselines, validating the effectiveness of using fragments relations on the long-term chatting task.

heading: 5 Conclusion
text: This work focuses on the challenge of isolated fragment processing in existing External Memory augmented Large Language Models (LLMs), proposing and formulating the fragment-level relations informed by intricate relations found within diverse long contexts. And we propose an efficacious method to integrate these fragment-level relations across distinct types of texts. Comprehensive experiments conducted over a range of long text processing tasks attest that the utilization of such fragment-level relations indeed enhances the performance of LLMs in various scenarios. We hope our findings will inspire further investigations into External Memory enhanced LLMs.
Limitation
Despite notable enhancement on external memory augmented LLMs through integrating fragmentlevel relations, the current implementation still suffers the following limitations: 1. Manual relation definitions and empirical parameter selection: The relation definitions as outlined in Equations 6, 7, 8 are empirically defined, which limits their generalizability. Additionally, the optimal values for relation parameters (wrel and α) vary based on text types, fragment lengths, and relation categories. We are, thus, limited to empirically selecting parameters that are good but not entirely optimal. This problem may be resolved through automatic relations definition based on LLM-driven optimization strategies. 2. Inapplicability to arbitrary retrieval methods: The relation incorporation method introduced in Section 3.3 only applies to retrieval methods that rely on fragment scores, thus neglecting other methods, such as generative retrieval. This limitation is worth further investigation in future work. 3. Limited validation: Although we have substantiated the advantages of fragment-level relations through numerous long text processing tasks such as long story understanding, repository-level code completion, and memory-enhanced chatbot, we still recognize the necessity for validation on more extensive and complex tasks, such as academic material library understanding with near-infinite length of context, and multi-agents interactive tasks with more complex fragment-level relations in the external memory of LLMs.

heading: Acknowledgment
text: This work is supported by Fundamental Research Funds for the Central Universities (226-2023- 00126). This work is also supported by the Major program of the National Natural Science Foundation of China (T2293720/T2293723).

heading: A Code Relation Calculation Details
text: Code Repository Graph G Construction. The code repository graph is created with the following steps: (1) For a specific code repository, we first construct the code syntax tree for every code source file using tree-sitter 1 (edge weight is set as 0.5). (2) In addition, we construct the file directory tree where every node corresponds to a file or directory in the repository (edge weight is set as 0.3). (3) Next, we connect the root node of every code syntax tree with its counterpart file node on the file directory tree (edge weight is set as 1.0), obtaining the code repository parsing tree. (4) Finally, we create node connections (edge weight is set as 0.8) between every function invoking node and its corresponding function definition node (including both in-file invoking and cross-file invoking).
Distance calculation. On code repository graph G, the edge weight is set according to the edge types (a connection between files, a connection between in-file code syntax node, etc. ), and constrained in [0, 1].
The length of a path through multiple nodes is defined as the product of the weights of all edges on the path, thus a longer path will have a smaller weight. The relation strength Dis(gcik , g ci l ) of the relationship between two nodes is defined as the weight of maximum weight path between the two nodes gcik and g ci l . We calculate Dis(·, ·) via the Dijkstra algorithm in our experiment.

heading: B Framework Implementation Details
text: B.1 Long Story Understanding Details
Prompt Template. We provide the prompt template used in the experiment of long story understanding in Prompt. 1.
Retrieval. We take same fragment splitting and embedding calculation method as LongBench (Bai et al., 2023). Contriever (Izacard et al., 2021) is used as the text embedding model. We experiment different fragment length (500 and 800 words) for different context length limitations.
LLM Inference. In the experiment, same context content are provided for different LLMs. The detail prompt template slightly varies in different LLMs according to their training template. For example, the prompt is covered with "
" and "
"
1https://tree-sitter.github.io
for Llama2. The temperature is set as 1.0 during inference.
B.2 Code Completion Framework Details Prompt Template. We provide the prompt template used in the experiment of repository-level code generation in Prompt. 2.
Retrieval. Every fragment consists of exactly Sw lines of code and adjacent fragments have Ss overlapped lines of code. We set Sw = 20 and Ss = 10 same as Zhang et al. (2023a). Following RepoCoder (Zhang et al., 2023a), the BM25 (Robertson and Zaragoza, 2009) is used for retrieval. The fragments with top 10 similarity scores to the completed code context are taken as retrieved results every time.
LLM Inference. We employ Codellama34b (Roziere et al., 2023) with 4K context length as the base LLMs in our experiment, and exactly the same prompt template as used in RepoCoder (Zhang et al., 2023a).
B.3 Memory-enhanced Chatbot Details Prompt Template. We provide the prompt template used in the experiment of chatbot in Prompt. 3 (for inference) and Prompt. 4 (for evaluation).
Retrieval. In MemRetrieval-ChatGPT (+FragRel), every fragment consists of exactly one turn of the dialog. The text embedding is calculated using the text-embedding-ada-002 model. Every time we load related historical fragments with top 8 similarity scores to the recent dialog (last turn of dialog and latest user prompt). Additionally, the retrieved fragments are reordered according to their chatting time.
LLM Inference. Same as MemoChat (Lu et al., 2023), we use the GPT-3.5-Turbo as the base LLM for inference, and the context length is constrained to 2K tokens. In the initial rounds of conversation, all historical records are directly inputted into the model. Once the length of the historical record exceeds 1K tokens or the conversation rounds surpass 10, the historical chat content will be stored in external memory. Subsequently, each conversation will load relevant fragments to the recent chatting context from the external memory.
Prompt 1: Prompt template in the experiment of long story understanding. You are given a story , which can be either a novel or a movie script , and a question
. Answer the question asconcisely as you can , using a single phrase if possible. Do not provide any explanation.
Story: {context}
Now , answer the question based on the story asconcisely as you can , using a single phrase if possible. Do not provide any explanation.
Question: {input}
Answer:
Prompt 2: Prompt template in the experiment of code generation. # Here are some relevant code fragments from other files of the repo: # ----------------- # the below code fragment can be found in: # ***.py # ----------------- # [RETRIEVED_CODE_CONTENT] # ----------------- # ***.py # ----------------- # [RETRIEVED_CODE_CONTENT] # ----------------- # ***.py # ----------------- # [RETRIEVED_CODE_CONTENT] # ----------------- ...
[CURRENT_FILE_CONTENT] ...
Prompt 3: System prompt used in the experiment of chatbot. You are an intelligent dialog bot. You will be shown Related Evidences supporting
for User Input , and Recent Dialogs between user and you. Please read , memorize , and understand given materials , then generate one concise , coherent and helpful response.
Prompt 4: Prompt template for evaluating the generated results with GPT-4. You are an impartial judge. You will be shown Related Conversation History , User
Question and Bot Response.
``` Related Conversation History [RCH_0] ```
``` User Question [UQ_1] ```
``` Bot Response [BR_2] ```
Please evaluate whether Bot Response is faithful to the content of Related Conversation History to answer User Question. Begin your evaluation by providing a short explanation , then you must rate Bot Response on an integer rating of 1
to 100 by strictly following this format: [[ rating ]].

heading: Future Work
text: This limitation is worth further investigation in future work. 3. Limited validation: Although we have substantiated the advantages of fragment-level relations through numerous long text processing tasks such as long story understanding, repository-level code completion, and memory-enhanced chatbot, we still recognize the necessity for validation on more extensive and complex tasks, such as academic material library understanding with near-infinite length of context, and multi-agents interactive tasks with more complex fragment-level relations in the external memory of LLMs