A page key-value cache cross-page block compaction and page block recycling feedback adjustment method and device and storage medium

By migrating across pages and updating slot-level mappings, the problem of inconsistency between logical compression and physical reclamation in existing technologies is solved, achieving efficient utilization of video memory resources and protection of model accuracy. It is suitable for large language model inference systems with paged key-value cache management.

CN123178294APending Publication Date: 2026-11-27ZHENGZHOU JUSHU TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611408227.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-11
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

In the inference process of large language models based on the Transformer architecture, the existing key-value caching compression method has inconsistent logical compression effect with the actual reclamation of physical page blocks in the paging management scenario. After merging, the representative vector cannot be moved forward as a whole according to the token order, which leads to the ineffective reclamation of physical page blocks, resulting in GPU memory resource pressure and model accuracy loss.

Method used

By migrating and merging the representative vector across physical pages and updating the block table mapping at the slot level, slot-level cross-block compaction and actual return of physical pages are achieved. The merging intensity is adjusted based on the actual number of returned physical pages, forming a closed-loop control.

Benefits of technology

It improves the reusability of physical page blocks, alleviates the pressure on GPU memory resources in long context and high-concurrency inference scenarios, improves the deployability of key-value cache merging and compression technology, and avoids unnecessary loss of model accuracy.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178294A_ABST
    Figure CN123178294A_ABST
Patent Text Reader

Abstract

The application discloses a page key value cache cross-page block compaction and page block recycling feedback adjustment method and device and a storage medium. After the key value vector is merged, the slot occupancy state of each physical page block is determined to determine a cross-physical page block migration scheme, all effective representative vectors in the physical page block to be migrated are migrated to the idle slot of the compatible physical page block together with the equivalent position and the base number metadata corresponding to the same slot index, the slot level block table mapping is updated to keep the attention calculation semantics unchanged, the physical page block is returned to the idle block pool of the physical page block allocator after all the physical page blocks to be migrated are idle, and the actual returned physical page block quantity instead of the logical compression rate is used to feedback and adjust the subsequent merging strength, thereby forming a closed loop of logical compression, physical recycling and strength adjustment. The application converts the dispersed idle slots formed by merging into complete physical page blocks that can be redistributed, thereby improving the video memory utilization rate of the paging cache.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence technology, specifically to a method, apparatus, and storage medium for adjusting cross-page block compaction and page block reclamation feedback in pagination key-value caching. Background Technology

[0002] In the inference process of large language models based on the Transformer architecture, in order to avoid repeatedly calculating the key vectors and value vectors corresponding to historical contexts, it is usually necessary to cache them into a key-value cache. As the context length and the number of concurrent requests increase, the memory usage of the key-value cache continues to grow, becoming an important factor limiting the throughput of the inference system and the length of contexts that can be served.

[0003] To improve video memory utilization efficiency, existing inference systems typically employ a paging-based key-value cache management approach, dividing video memory into multiple fixed-capacity physical pages and maintaining the mapping relationship between logical pages and physical pages through a block table. Building upon this, existing technologies have proposed various key-value cache compression methods, including importance-based eviction methods and information fusion-based merging methods. The former reduces cache size by deleting some low-importance key-value vectors, while the latter reduces logical storage by merging multiple key-value vectors into a smaller number of representative vectors. These methods typically use the number of evicted, merged, or reduced key-value vectors as the primary evaluation metric for compression effectiveness.

[0004] However, in a paging management architecture, physical pages are typically allocated and reclaimed as whole blocks. Even if a large number of key-value vectors are deleted or merged after compression, if a physical page still retains some valid data, that physical page usually cannot be returned to the allocator. Especially during fine-grained eviction or merging processes, the released free slots are often scattered across multiple physical pages, forming irregular intra-page holes. This can result in a high logical compression ratio, but a small or even zero number of actually reclaimable physical pages.

[0005] To address the aforementioned issue of in-page holes, existing technologies employ two main approaches. One approach involves pruning or eliminating entire blocks in a paginated layout, naturally aligning the released space with physical page blocks. However, this method only supports deletion-based compression and cannot utilize the contextual information preserved by information fusion-based merging. The other approach involves shifting the remaining key-value vectors forward in token order after pruning and reloading them, thus releasing the tail-end physical page blocks. However, this method relies on the premise of a one-to-one correspondence between key-value vectors and original tokens and a well-defined relative order. After information fusion-based merging, the position of the representative vector becomes a weighted composite value of multiple original positions, the token order is no longer a well-defined total order, and the overall forward shift requires moving almost all remaining data, a cost far exceeding the necessary cost. Furthermore, existing merging methods typically use the number of merged or reduced key-value vectors as a feedback indicator to adjust the compression intensity. Even with a high logical compression ratio but zero physical page block reclamation, the compression intensity continues to increase, causing unnecessary loss of model accuracy. Therefore, existing key-value cache compression methods still suffer from inconsistencies between logical compression effects and actual physical memory release in paging management scenarios. Further optimization is needed to ensure that the compressed, scattered free space is more effectively converted into realizable complete physical page blocks while maintaining the semantics of the merged representative vector access, and to correlate the compression intensity adjustment with the actual physical reclamation results. Summary of the Invention

[0006] To address the technical issues of existing key-value cache compression methods in pagination management scenarios, such as inconsistencies between logical compression and actual physical page block reclamation, and the inability to use the token-order-based overall forward-shifting compression method for the merged representative vector, this application provides a method for cross-page block compression and page block reclamation feedback adjustment in paginated key-value caches, comprising the following steps:

[0007] After merging multiple original key-value vectors in at least one logical page, a migration scheme is determined based on the slot occupancy status of each physical page block to make all slots of at least one physical page block free through cross-physical page block migration. The migration scheme indicates the physical page block to be migrated out and other physical page blocks for receiving representative vectors from the physical page block to be migrated out. The other physical page blocks are physical page blocks that belong to the same inference request, the same network layer, and the same attention head group as the physical page block to be migrated out, and are not shared by multiple logical pages.

[0008] According to the migration scheme, all valid representative vectors in the physical page block to be migrated out are migrated to the free slots of the other physical page blocks, and the metadata corresponding to each representative vector is migrated synchronously with the representative vector, so that all slots in the physical page block to be migrated out become free; wherein, the representative vector includes a merged representative vector obtained by merging multiple key-value vectors and a single key-value vector that did not participate in the merging and has a cardinality of 1, and the metadata includes at least the equivalent position used to characterize the comprehensive position of the multiple original key-value vectors that participated in generating the representative vector in the sense of position encoding and the cardinality used to characterize the number of the original key-value vectors, and the metadata and the representative vector are stored with the same physical page block identifier and slot index;

[0009] The slot-level mapping of the corresponding logical page in the block table is updated according to the physical page block identifier and slot index where the representative vector is located after migration. The block table records the physical page block identifier and slot index where each representative vector contained in each logical page is located.

[0010] After the block table update is completed, all physical page blocks to be migrated out with all slots in an idle state are returned to the idle block pool of the physical page block allocator; and

[0011] The number of physical pages actually returned to the free block pool is counted, and the merging strength of subsequent merging of pagination key-value cache is adjusted based on the number of physical pages actually returned rather than the logical compression rate, so that the above key-value vector merging, cross-physical page migration and physical page return form a closed loop with the merging strength.

[0012] The present invention also provides a pagination key-value cache cross-page block compaction and page block reclamation feedback adjustment device, comprising:

[0013] The migration scheme determination module is used to determine, after merging multiple key-value vectors in at least one logical page, a migration scheme that can make all slots of at least one physical page block free through cross-physical page block migration, based on the slot occupancy status of each physical page block; wherein, the migration scheme indicates the physical page block to be migrated out and other physical page blocks for receiving representative vectors in the physical page block to be migrated out, wherein the other physical page blocks are physical page blocks that belong to the same inference request, the same network layer and the same attention head group as the physical page block to be migrated out, and are not shared by multiple logical pages.

[0014] The cross-block compaction execution module is used to migrate all valid representative vectors in the physical page block to be migrated out to the free slots of other physical page blocks according to the migration scheme, and to migrate the metadata corresponding to each representative vector synchronously with the representative vector, so that all slots in the physical page block to be migrated out become free; wherein, the representative vector includes a merged representative vector obtained by merging multiple key-value vectors and a single key-value vector that did not participate in the merging and has a cardinality of 1, and the metadata includes at least the equivalent position used to characterize the comprehensive position of the multiple original key-value vectors participating in the generation of the representative vector in the sense of position encoding and the cardinality used to characterize the number of the original key-value vectors;

[0015] The mapping update module is used to update the slot-level mapping of the corresponding logical page in the block table according to the physical page block identifier and slot index where the representative vector is located after migration. The block table records the physical page block identifier and slot index where each representative vector contained in each logical page is located.

[0016] The physical recycling module is used to return physical page blocks with zero occupied slots and a free slot bitmap indicating all slots are free to the free block pool of the physical page block allocator after the block table update is completed; and

[0017] The feedback adjustment module is used to count the number of physical page blocks actually returned to the free block pool during the current compaction cycle, and update the control parameters that characterize the marginal cost of unit video memory resources based on the number of physical page blocks actually returned and the deviation of the current occupied video memory amount relative to the target video memory amount. Then, based on the updated control parameters, the module adjusts the number of logical pages and / or the merging ratio for subsequent merging of paging key-value cache.

[0018] The present invention also provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the above-described method.

[0019] Technical effects and advantages of the invention: This invention forms a complete technical closed loop under the paginated key-value caching architecture, from "logical merging and compression" to "slot-level cross-block compaction and actual physical page block return" and then to "feedback adjustment of logical compression intensity based on the actual number of returned physical page blocks". First, by storing and migrating the representative vector and its equivalent position, cardinality, and other metadata in a one-to-one correspondence with the same physical page block identifier and slot index, and by using slot-level block table mapping, the physical movement is made semantically transparent to attention calculation, solving the problem that the representative vector after merging no longer corresponds one-to-one with the original token and cannot be compressed by moving forward in token order. Second, by cross-block migration and binning feasibility determination for low-occupancy pages, scattered idle slots are aggregated into physical page blocks that can be returned in whole blocks with less data movement, solving the problem of high logical compression rate but zero actual reclaimable physical page blocks. Third, the merging intensity is adjusted by using the number of physical page blocks actually returned to the idle block pool, rather than the logical compression rate, to avoid unnecessary loss of model accuracy caused by continuously increasing the merging intensity when logical compression cannot be converted into physical reclamation. This improves the reusability of physical page blocks within the paging cache pool, alleviates the pressure on GPU memory resources in long context and high-concurrency inference scenarios, and enhances the deployability of key-value cache merging and compression technology in actual paging inference systems. Attached Figure Description

[0020] Figure 1 A flowchart of the video memory reclamation method provided by the present invention.

[0021] Figure 2 This is a flowchart illustrating the process of determining a migration scheme in the method of the present invention.

[0022] Figure 3 This is a flowchart illustrating how the subsequent merging intensity is adjusted based on the actual number of physical pages returned in the method of this invention.

[0023] Figure 4 This is a flowchart illustrating the three-way decision-making process for retaining, eliminating, and merging candidate logical pages in the method of this invention.

[0024] Figure 5 This is a structural diagram of the device provided by the present invention. Detailed Implementation

[0025] The technical solution of the present invention will be further described below with reference to the accompanying drawings and embodiments. The described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0026] refer to Figure 1This invention provides a method for adjusting cross-page block compaction and page block reclamation feedback in pagination key-value caching. For example... Figure 1 As shown, the method includes steps S1 to S5:

[0027] S1. After merging multiple key-value vectors in at least one logical page, based on the slot occupancy status of each physical page block, determine a migration scheme that can make all slots of at least one physical page block free through cross-physical page block migration; wherein, the migration scheme indicates the physical page block to be migrated out and other physical page blocks for receiving representative vectors in the physical page block to be migrated out, wherein the other physical page blocks are physical page blocks that belong to the same inference request, the same network layer and the same attention head group as the physical page block to be migrated out, and are not shared by multiple logical pages;

[0028] S2. According to the migration scheme, all valid representative vectors in the physical page block to be migrated out are migrated to the free slots of the other physical page blocks, and the metadata corresponding to each representative vector is migrated synchronously with the representative vector, so that all slots in the physical page block to be migrated out become free; wherein, the representative vector includes a merged representative vector obtained by merging multiple key-value vectors and a single key-value vector that did not participate in the merging and has a cardinality of 1, and the metadata includes at least an equivalent position and a cardinality, and the metadata and the representative vector are stored with the same physical page block identifier and slot index;

[0029] S3. Update the slot-level mapping of the corresponding logical page in the block table according to the physical page block identifier and slot index where the representative vector is located after migration. The block table records the physical page block identifier and slot index where each representative vector contained in each logical page is located.

[0030] S4. After the block table update is completed, return all physical page blocks to be migrated out with all slots in an idle state to the idle block pool of the physical page block allocator; and

[0031] S5. Count the number of physical pages actually returned to the free block pool, and adjust the merging strength of subsequent merging of pagination key-value cache based on the number of physical pages actually returned rather than the logical compression rate, so that the above key-value vector merging, cross-physical page migration and physical page block return form a closed loop with the merging strength.

[0032] This invention is applicable to large language model inference systems employing a paginated key-value caching management approach. In one specific implementation, the large language model can be an autoregressive generative model based on a Transformer structure. During the pre-filling or decoding phase, the key vectors and value vectors corresponding to historical tokens are cached for subsequent attention calculations. Hereinafter, the key vector and value vector corresponding to a token are collectively referred to as a key-value vector.

[0033] In practical implementations, a key-value vector can contain key and value data from a single Transformer layer, or it can represent the key-value data corresponding to the same token across multiple attention heads, a single attention head, or a group of attention heads. For implementations employing a hierarchical cache management approach, different network layers can execute the method of this invention separately, or a unified cache management module can coordinate and manage multiple network layers.

[0034] In a paginated key-value cache architecture, logically contiguous key-value data is not required to be stored contiguously in video memory. Instead, it is divided into multiple logical pages according to a fixed number of key-value entries, and corresponding physical page blocks are allocated to each logical page. Each physical page block includes multiple slots that can store key-value data.

[0035] For ease of explanation, the number of slots that a physical page block can accommodate can be defined as `block_size`. For example, `block_size` can be 8, 16, 32, 64, or other values ​​suitable for the target hardware and inference framework. In a preferred embodiment, `block_size` is 16, meaning that one physical page block can store 16 ordinary key-value entries or 16 representative vectors formed by merging multiple key-value entries. This invention does not require the logical page capacity to be bound to a specific value; it only requires that the physical page block can accommodate key-value entries in units of multiple slots.

[0036] Physical pages are managed uniformly by the physical page block allocator. When an inference request needs to increase key-value cache space, the physical page block allocator retrieves the corresponding physical page block from the free block pool and allocates it to the inference request; when all valid data in a physical page block has been released, the physical page block can be returned to the free block pool and made available for use by other inference requests.

[0037] The term "video memory reclamation" in this invention refers to the process of physical page blocks being returned to the free block pool of the paging cache allocator, thereby enabling their reallocation to other inference requests. The unit of measurement is the number of physical page blocks returned. This is a different concept from the decrease in the total video memory allocation of processes at the device driver level. In the implementation of the paging cache pool reserving video memory at service startup, the latter does not necessarily change immediately with the return of physical page blocks. In paging management scenarios, physical page blocks are the actual basic unit for video memory resources to be rescheduled. Even if a physical page block retains only one valid key-value vector, as long as that vector still exists, the physical page block usually cannot be returned to the allocator as a whole. Therefore, this invention focuses not only on how many key-value entries are logically reduced, but also specifically on whether logical compression can generate truly returnable, complete free physical page blocks.

[0038] Logical pages and physical page blocks are mapped through a block table. For ordinary paging key-value caches that do not perform fine-grained merging and cross-block compaction, the block table can be maintained in the form of one logical page corresponding to one physical page block or one logical block number corresponding to one physical block number.

[0039] In one embodiment of the present invention, after the key-value vectors are merged and subsequently migrated across physical page blocks, multiple representative vectors in the same logical page may no longer all be located in the original same physical page block. Therefore, the block table can be further expanded into slot-level mapping information, as shown in the table below:

[0040] Fields type illustrate logical_page_id uint32 Logical page identifier Slot List (uint32, uint16) array Each logical page represents the vector located in (block_id, slot_idx).

[0041] Slot-level mapping information can be represented as a correspondence between logical_page_id and multiple (block_id, slot_idx) pairs, where block_id represents the physical page block identifier and slot_idx represents the slot index of the representative vector in the corresponding physical page block. Through this mapping information, even if the representative vector in a logical page is distributed across multiple physical page blocks, the attention computation kernel can still sequentially read the corresponding representative vector according to the slot-level mapping, thus making the change in the position of the representative vector in physical memory transparent to the logical key-value access process.

[0042] Before implementing the method of this invention, multiple key-value vectors in at least one logical page are first merged. The merging can employ any merging algorithm capable of converting multiple key-value vectors into a smaller number of representative key-value vectors. Therefore, this invention is applicable as long as there are n key-value vectors represented as m representative vectors after merging, and m is less than n, thereby reducing the number of valid entries in the physical slots.

[0043] In this invention, "representative vector" is a general term for valid key-value vectors in physical slots. It includes merged representative vectors (obtained by merging multiple original key-value vectors with a cardinality greater than 1) and single key-value vectors (not involved in merging, corresponding to only one original key-value vector, with a cardinality of 1). The merged physical page block may contain both types of entries simultaneously. For example, in a logical page, only some key-value vectors satisfy the similarity condition and are merged, while the remaining key-value vectors remain unchanged. During cross-block compaction, all valid representative vectors in the physical page block to be migrated (regardless of their cardinality, whether 1 or greater) are considered for migration. Only in this way can it be guaranteed that all slots in the physical page block to be migrated become idle and meet the conditions for returning the entire block after migration. For a single key-value vector with a cardinality of 1, its equivalent position is the original token position, and its migration is completely identical to the migration of merged representative vectors on the data path.

[0044] For example, a logical page corresponds to a physical page block containing 16 slots. Before merging, all 16 slots are occupied by 16 key-value vectors. After similarity calculation, the 16 key-value entries can be divided into 6 groups, and each group can be merged into a representative vector. At this point, the physical page block only needs to store 6 representative vectors, which is equivalent to creating 10 free slots.

[0045] The 10 free slots do not need to be contiguous in the physical page block. If the original members of different merging groups are distributed in different slots, one slot can be selected to store the merging representative vector, and the slots corresponding to other key-value entries in the same group can be released; alternatively, any available slot can be reselected to store the representative vector. Therefore, the free slots generated after merging may be discontinuous or irregularly distributed. This invention is specifically designed to further implement cross-physical page block compaction for such scattered voids.

[0046] In a preferred embodiment, metadata corresponding to each representative vector is generated simultaneously. This metadata describes the additional semantic information that the representative vector needs to retain in subsequent attention calculations after being merged from multiple original key-value vectors.

[0047] Preferably, the metadata includes at least an equivalent position and a cardinality. The equivalent position characterizes the combined position of the multiple original key-value vectors involved in generating the representative vector in a positional encoding sense, and the cardinality characterizes the number of original key-value vectors involved in generating the representative vector. For example, if a representative vector is formed by fusing four original key-value vectors, its cardinality can be set to 4; if the representative vector is not fused with other key-value vectors and corresponds to only one original key-value vector, the cardinality can be set to 1.

[0048] In one specific implementation, if the original position of the j-th key-value entry participating in the fusion is... The corresponding fusion weight is , then represents the equivalent position of the vector. It can be determined based on multiple original locations and fusion weights, for example, it can be done by:

[0049]

[0050] When the fusion weights have been normalized When the above formula is used, it can be simplified to:

[0051]

[0052] Equivalent positions are not limited to linear weighted averages; other calculation methods can be determined based on the position encoding form and merging algorithm, as long as they can represent the original positional relationship corresponding to the representative vector in subsequent attention calculations.

[0053] The metadata representing a vector can be stored in various physical storage methods. In one implementation, a metadata storage area can be set up in each physical slot for both key-value data and corresponding metadata; that is, a slot contains the representative key, representative value, and also the metadata of the representative vector. And card. In another implementation, to maintain the original key-value data layout, a metadata array can be set that is independent of the key-value data array but corresponds one-to-one with the slot index. The contents of the metadata array are shown in the table below:

[0054] Fields type illustrate pos_star float32 or uint32 fixed point Equivalent position card uint16 cardinality

[0055] For example, if the key-value data in the i-th physical slot is stored in the key-value buffer [i], then the equivalent position and cardinality corresponding to that slot are stored in position_buffer[i] and cardinality_buffer[i], respectively. In this way, as long as the key-value buffer, position_buffer, and cardinality_buffer use the same block_id and slot_idx indexes, the metadata corresponding to any representative vector can be quickly determined.

[0056] The advantage of using the aforementioned one-to-one correspondence storage method is that when the representative vector moves across physical page blocks, its metadata can be synchronously moved according to the same slot index, avoiding mismatches between the representative vector and its equivalent location or cardinality. This is especially important when the representative vector is formed by merging multiple original key-value entries; if an incorrect equivalent location or cardinality is read after migration, it may affect subsequent positional encoding or attention normalization results. Therefore, establishing a stable one-to-one correspondence between metadata and the representative vector helps ensure the consistency of attention calculation semantics before and after cross-block migration.

[0057] After merging the key-value vectors of one or more logical pages, the slot occupancy status of each physical page block can be determined. The slot occupancy status at least reflects which slots in the corresponding physical page block are occupied by representative vectors or ordinary key-value entries, and which slots are currently idle. In a preferred embodiment, an empty slot registration table can be maintained for each physical page block, as shown in the table below:

[0058] Fields type illustrate block_id uint32 Physical page block identifier occupied_count uint16 Number of slots already occupied free_slot_bitmap uint16 (when block_size=16) Free slot location map

[0059] The free slot registration table includes at least block_id, occupied_count, and free_slot_bitmap. Among them, block_id is the physical page block identifier; occupied_count is the number of slots in the physical page block that are currently occupied by valid key-value entries or representative vectors; free_slot_bitmap is a free slot bitmap, and its bit width can be the same as block_size.

[0060] For example, when block_size is 16, free_slot_bitmap can be represented by a 16-bit unsigned integer, where the i-th bit being 1 indicates that the i-th slot is free, and the i-th bit being 0 indicates that the i-th slot is occupied. Of course, the opposite encoding rule can also be used, as long as it is possible to determine whether each slot is free based on the bitmap.

[0061] In other implementations, instead of using a bitmap, a free slot index list, range table, linked list, or other data structure capable of recording free locations can be used. The bitmap approach can utilize hardware bitwise operations to perform free slot detection, first free slot lookup, and free slot count, and requires only a small amount of additional storage space per physical page block.

[0062] Slot status can be incrementally updated as the key-value cache status changes. For example, after key-value vector merging, released slots are updated to free in the `free_slot_bitmap`, and `occupied_count` decreases accordingly; after a new key-value entry is written to an empty slot, the corresponding bitmap position is updated to occupied, and `occupied_count` increases accordingly; during cross-block migration, the target slot changes from free to occupied, and the source slot changes from occupied to free after the migration is confirmed; after a physical page block is returned to the allocator, its status record is deleted from the active page block set or marked as free. Using an event-driven incremental update approach eliminates the need to rescan all key-value cache data before each compaction operation, reducing slot status maintenance overhead.

[0063] After obtaining the slot occupancy status of each physical page block, it is necessary to determine whether there is a migration scheme that can completely empty one or more physical page blocks through cross-physical page block migration. The migration scheme needs to determine whether the total capacity of empty slots scattered across different physical page blocks and the amount of valid data in the source physical page block meet the reloading conditions.

[0064] For example, if a candidate source physical page block contains only 2 representative vectors, and there are at least 2 free slots in other physical page blocks that can be used to receive the representative vectors, then theoretically these 2 representative vectors can be moved out, making the source physical page block completely empty, thus meeting the conditions for returning the entire block.

[0065] In a preferred embodiment, candidate physical page blocks can be arranged in ascending order of their occupied_count. This sorting can be performed as a full sort during each compaction, or a min-heap, bucket index, or linked list categorized by occupied_count can be maintained during normal operation to quickly obtain the physical page block with the lowest occupancy. Because block_size is usually a fixed and small integer, such as 16 or 32, the range of occupied_count is also small. In this case, using bucketing based on occupancy count can obtain the page block with the lowest occupancy at a lower cost. For example, a bucket can be set up for occupied_count = 0, 1, 2... block_size, and each bucket records the identifier of the physical page block with the corresponding occupancy. When the occupancy of a physical page block changes, it only needs to be moved from the original bucket to the new bucket.

[0066] Figure 2 The diagram shown is a flowchart illustrating a migration scheme provided in this application, including:

[0067] S201. Select candidate physical page blocks to be migrated out in ascending order of occupied_count;

[0068] S202. Accumulate the number of representative vectors to be migrated in the candidate physical page blocks to be migrated out, and count the number of free slots available in each of the remaining physical page blocks;

[0069] S203. Determine if the binning condition is met. If it is, identify the candidate page block as the page block to be migrated and continue expanding the set of physical page blocks to be migrated. Otherwise, stop expanding and output the number of physical page blocks N_free that can be completely vacated. When determining the migration plan, start with the physical page block with the smallest occupied_count, assume it as the physical page block to be migrated, and calculate the number of representative vectors to be moved to completely vacate this physical page block. Then, determine if the total number of free slots provided by other physical page blocks besides the physical page block to be migrated is sufficient. If it is sufficient, it means that at least one physical page block can be vacated.

[0070] The second low-occupancy physical page block can be added to the set of physical page blocks to be migrated, accumulating the number of representative vectors to be migrated. Then, it can be reassessed whether the total number of free slots provided by other physical page blocks outside the set of physical page blocks to be migrated is sufficient to accommodate these representative vectors. Using this method, the number of complete free physical page blocks that can be formed through cross-page migration in the current state can be calculated.

[0071] For example, let S be the set of physical pages to be migrated out, and o_i be the occupied_count of the i-th physical page in S. Then the total number of representative vectors to be migrated can be expressed as C_move = Σo_i. Let C_free be the total number of free slots that other active physical pages besides the set of physical pages to be migrated out can provide. Then, when C_free ≥ C_move, the physical pages in set S can theoretically be completely vacated. By gradually expanding the set of physical pages to be migrated out, S, we can obtain the number of physical pages that can be vacated simultaneously, N_free. In practical implementation, to avoid repeatedly calculating C_free, we can pre-calculate the total number of free slots S_free in all active physical pages, and then deduct the original free slots of the candidate source pages themselves or recalculate the available capacity according to the target page set when expanding the candidate source set.

[0072] Judging whether a page can be vacated based solely on the total number of free slots, C_free ≥ C_move, is a necessary but not sufficient condition. For example, a candidate source physical page block contains 5 representative vectors, and there are exactly 5 other physical page blocks, each with only 1 free slot. In this case, C_free = 5 = C_move satisfies the total quantity condition. If the implementation allows the representative vectors of a source page block to be dispersed and moved into multiple target page blocks, then the source page block can be vacated. However, if the implementation requires that the representative vectors of the same source page block be moved into the same target page block as much as possible to reduce the dispersion of the block table, then no single target page block can accommodate these 5 representative vectors, and the total quantity judgment will produce a misjudgment.

[0073] Therefore, in a preferred embodiment, the feasibility of the migration scheme is determined by binning conditions: first, the total number of free slots available from the remaining physical page blocks outside the candidate set to be migrated S is not less than the total number of representative vectors to be migrated; second, for each physical page block in S, its representative vectors to be migrated can be allocated to one or more target physical page blocks, and the number of free slots in each target physical page block is not less than the number of representative vectors allocated to it. In the implementation that allows distributed migration, condition two degenerates into condition one; in the implementation that requires centralized migration, condition two requires that there exists at least one target page block with a number of free slots not less than the occupied_count of the source page block. Binning determination can be implemented using a first-fit or best-fit greedy strategy in descending order of the number of free slots in the target page blocks. Its computational complexity is linearly related to the number of active physical page blocks and will not cause significant overhead to the decoding process.

[0074] In a preferred embodiment, subsequent cross-block compaction is triggered only after the above calculations confirm that at least one complete physical page block can be freed. A threshold value N_threshold for the number of complete reclaimable physical pages can also be set. For example, compaction is allowed when N_free ≥ 1; or, considering the memory access cost of compaction, N_threshold can be set to 2, 3, or other values, and compaction is only performed when it is expected that at least the corresponding number of physical pages can be reclaimed. By setting a threshold for the number of complete reclaimable physical pages, frequent migration of large amounts of key-value data for the purpose of reclaiming only a very small amount of physical resources can be avoided.

[0075] In addition to the threshold for the number of complete reclaimable physical page blocks, a preset free slot threshold can also be set. For example, the total number of free slots S_free in all currently active physical page blocks can be compared with a preset free slot threshold (such as block_size or a multiple of block_size). If S_free has not yet reached a sufficient number to form a complete physical page block, there is no need to perform cross-page compaction.

[0076] A proportional threshold can also be set, for example, only entering the migration scheme evaluation process when S_free is not less than a preset proportion of the total number of slots in the active physical page block. Using the total number of slots with lower computational cost as the first-level filtering condition, and only executing migration planning when fragmentation accumulates to a certain level, can reduce the interference of compaction management logic on the normal decoding process.

[0077] In another preferred embodiment, the migration cost and recovery benefits can be calculated before executing the migration scheme. The migration cost can be determined based on the number of representative vectors to be moved. For example, C_move can be used directly as the migration cost indicator, or the number of data bytes, attention heads, layers, key and value sizes, and metadata size of each representative vector can be further considered to estimate the actual number of bytes read and written to the video memory. If the total number of bytes for each representative vector and its corresponding metadata is D_vec, then a migration typically requires at least one source address read and one destination address write. Therefore, the expected amount of video memory to be moved can be approximately expressed as 2 × C_move × D_vec, and the expected amount of video memory to be moved is used as the migration cost.

[0078] The benefits of reclamation can be determined based on the number of physical page blocks that can be completely freed. For example, if the actual cache space occupied by a physical page block is D_block, then the expected reclaimed GPU memory space can be expressed as N_free × D_block. Since the paging key-value cache pool may have reserved GPU memory entirely at service startup in some inference systems, "reclamation" does not necessarily mean that the requested GPU memory at the device driver level immediately decreases. Instead, it means that physical page blocks are returned to the paging cache allocator's free block pool, and can be reallocated to new inference requests later. Therefore, the benefits of reclamation can also be directly measured by N_free or the number of blocks added to the free block pool.

[0079] In one implementation, a cost-benefit coefficient β can be set, and migration is performed only when C_move (migration cost) is less than a preset cost-benefit condition that is satisfied between β and a normalized value of the recovery benefit. For example, the physical page block capacity can be converted into the same number of slots, requiring C_move ≤ β × N_free × block_size, where β can be set to 0.5, 1, 1.5, or other values ​​according to acceptable migration overhead. Alternatively, the GPU memory copy bandwidth and decoding cycle time can be actually measured, and the estimated migration time T_move can be compared with the expected resource benefit from releasing physical blocks. The migration scheme is executed only when T_move is less than a preset latency budget. Compared to simply performing page block defragmentation periodically, using cost-benefit judgment can avoid a large amount of invalid data migration when holes are too scattered or the number of migrations is too large.

[0080] When determining the specific physical page blocks to be migrated out, it is preferable to select those with a smaller occupied_count. The amount of data required to completely empty a physical page block is proportional to the number of remaining valid representative vectors within it. Therefore, all other things being equal, prioritizing the migration out of physical page blocks with lower occupancy can achieve complete physical page block reclamation with less data migration.

[0081] When determining the physical page blocks to be migrated, the best fit principle can be prioritized. This means prioritizing physical page blocks with sufficient free slots and fewer remaining free slots after accommodating the current representative vectors to be migrated. For example, if a source physical page block contains 3 representative vectors to be migrated, and there are target candidate page blocks A and B, where A has 3 free slots and B has 8 free slots, then it is preferable to migrate these 3 representative vectors to A. After the migration, A becomes fully loaded, while B still retains 8 free slots, which can be used to accommodate other source page blocks. Compared to randomly selecting target page blocks, the best fit can reduce the creation of new scattered holes during the migration operation, making the remaining free space as concentrated as possible, thereby improving the feasibility of subsequent compaction.

[0082] When determining the incoming physical page blocks and their constituent sets, it is also necessary to ensure compatibility between the incoming physical page blocks and the physical page blocks to be migrated out. In a preferred embodiment, the incoming physical page block should belong to the same inference request, the same network layer, and the same attention head group as the physical page block to be migrated out, and the incoming physical page block should not be shared by multiple logical pages, i.e., its reference count is 1. The above compatibility conditions are used to avoid mixing representative vectors belonging to different requests into the same physical page block, which would prevent the entire block from being released when the request ends, and to avoid cross-layer or cross-head group misalignment, which would lead to incorrect data reading in attention calculation. For inference systems that use prefix sharing or copy-on-write mechanisms, physical page blocks with a reference count greater than 1 are neither considered as physical page blocks to be migrated out nor as physical page blocks to be migrated in, thereby ensuring that cross-block compaction does not affect the correctness of the shared prefix. In implementation, request_id, layer_id, head_group_id, and ref_count fields can be added to the empty slot registration table. When filtering candidate incoming page blocks, the above fields are used for filtering first, and then the best fit principle is used to select from compatible page blocks.

[0083] The following specific examples illustrate the beneficial effects of slot-level migration across physical pages:

[0084] Given block_size = 16, a certain inference request occupies 4 physical page blocks B0 to B3, each page initially fully occupied (16 / 16). After page-level merging, the number of representative vectors in each page are 3, 5, 2, and 14 respectively, i.e.:

[0085] B0: 3 occupied, 13 free

[0086] B1: 5 occupied, 11 free

[0087] B2: Occupied 2, Idle 14

[0088] B3: 14 occupied, 2 free

[0089] At this point, the logical compression rate is 1 − (3+5+2+14) / 64 = 62.5%, but none of the four physical page blocks are completely empty. According to the whole block return constraint, the number that can be returned is 0, and the video memory usage remains unchanged.

[0090] If in-page defragmentation is used (moving the in-page representative vector forward to concentrate holes at the end of the page), B0 becomes occupied in the first 3 slots and free in the last 13 slots—but this page block is still partially occupied and cannot be returned. In-page defragmentation does not change the eligibility of any physical page block to be returned.

[0091] If we adopt the method of shifting the entire token forward in order (i.e., the conventional approach of expulsion-class compaction), the vectors in B1, B2, and B3 need to be shifted forward sequentially to fill the empty slots in B0. However, the resulting representative vector no longer corresponds one-to-one with the original tokens, and its equivalent position... For a weighted average, multiple representative vectors They may fall into similar intervals, and the "token order" no longer constitutes a well-defined total order after merging; moreover, the overall forward shift requires moving 5+2+14 = 21 representative vectors.

[0092] The method of this invention is as follows: Select B2 (occupying 2 slots), B0 (occupying 3 slots), and B1 (occupying 5 slots) as candidates for migration in ascending order of occupancy. The remaining pages can provide free slots. First, migrate 2 vectors from B2 to 2 empty slots in B3, leaving B2 completely empty. Then, migrate 3 vectors from B0 to empty slots in B1, leaving B0 completely empty. At this point, B1 occupies 8 slots and B3 occupies 16 slots. A total of 5 representative vectors are moved, resulting in N_free = 2 completely empty physical page blocks, which are then returned to the allocator, resulting in an actual memory reduction of 50%.

[0093] As the comparison shows, moving 5 vectors can actually free up 2 physical pages, while moving 21 vectors sequentially forward or moving several vectors within a page cannot yield any returnable physical pages. Cross-page migration, ascending order of occupancy, and optimal fit migration are necessary and efficient ways to transform irregular gaps after merging into whole free blocks.

[0094] Empty slots generated by logical compression are not directly converted into physical page block releases; by regrouping scattered holes through cross-page migrations targeting low-occupancy pages, the number of real realizable physical page blocks in the physical cache pool can be increased.

[0095] When performing a representative vector migration, in addition to the key and value data themselves, the metadata corresponding to the representative vector also needs to be processed synchronously. "Synchronous migration" does not require the hardware to complete all data writing within the same clock cycle; its core principle is that after the migration, the one-to-one correspondence between the representative vector and its metadata remains unchanged. That is, if the representative vector R and its metadata M in the source address (block_s, slot_s) are migrated to the target address (block_d, slot_d), then after the migration, R and the corresponding M should be available at (block_d, slot_d), and subsequently, when accessing R through the block table, the correct M should also be read.

[0096] In a relatively safe migration sequence, the representative vector and its corresponding metadata are first written to the target free slot; after confirming the writing is complete, the block table is updated so that the logical access address points to the new (block_id, slot_idx); finally, the source slot is released. Adopting the order of "write to target first, then update mapping, and finally release source location" ensures that at any point during the migration process, the location pointed to by the block table always contains valid data. Even in a GPU asynchronous execution environment, CUDAevent, stream synchronization, kernel execution boundaries, version numbers, or other synchronization mechanisms can ensure that the block table does not prematurely point to a target slot that has not yet been written.

[0097] Preferably, cross-page compaction can be scheduled to be performed between two adjacent decoding steps. For example, compaction can be performed after the current decoding step completes attention calculation and writes new key-value data, and before the next decoding step begins reading the key-value cache. This avoids the currently executing attention kernel accessing the migrated data simultaneously. In high-concurrency inference scenarios, completely stopping all requests for global compaction would cause significant pauses. Therefore, compaction tasks can be fragmented by request, by layer, by key-value cache partitioning, or by GPU stream, and local concurrency can be achieved through block table version control.

[0098] For example, the block table can assign a version number (V0) to each logical page. Before migration begins, the old version V0 is recorded. After the target data is written and a new block table entry is constructed, the version is atomically switched to V1. When reading a logical page, the attention kernel first reads the version number, then reads the mapping list. If the version number has changed by the end of the read, the corresponding mapping is retrieved again. By using versioned mappings, the impact of large-scale synchronization operations on inference throughput can be further reduced.

[0099] After the block table is updated, the source slot can be marked as free, and the occupied_count and free_slot_bitmap of both the source and target physical page blocks can be updated synchronously. For the target physical page block, the bitmap position corresponding to the newly occupied slot should be updated to occupied; for the source physical page block, the original slot should be updated to free. If the occupied_count of the source physical page block becomes 0, it means that the physical page block no longer contains any valid key-value data. At this time, the free_block, release_block, or other equivalent interfaces provided by the physical page block allocator can be called to return the physical page block to the free block pool.

[0100] Preferably, before actually returning physical page blocks, it can be verified again whether `free_slot_bitmap` represents all free spaces, or whether `occupied_count` is 0, thereby avoiding the release of physical page blocks still containing valid data due to status registration errors. For the implementation with `block_size=16`, if it is agreed that 1 in the location graph represents free space, then it can be determined whether `free_slot_bitmap` is equal to 0xFFFF; if it is agreed that 0 represents free space, then it can be determined whether `free_slot_bitmap` is equal to 0. Using dual verification of `occupied_count` and `free_slot_bitmap` can improve the security of the physical page reclamation process.

[0101] After multiple representative vectors within the same logical page are migrated, the block table can use a slot-level mapping list to store the new physical locations. For example, if logical page P originally corresponds to physical page block B0, after merging, only representative vectors R0, R1, and R2 are retained. After compaction, they are stored in slot 2 of B5, slot 7 of B5, and slot 1 of B8, respectively. Then the block table can be represented as P→[(B5, 2), (B5, 7), (B8, 1)]. When the attention kernel processes logical page P, it reads R0, R1, and R2 according to this slot list, and reads their corresponding equivalent positions and cardinality. Since the logical order of the representative vectors can be determined by the order in the list, equivalent positions, or other logical identifiers, their slot_idx in physical memory does not need to reflect the original token position.

[0102] In a preferred embodiment, the relative order of the migrated representative vectors within the same logical page can be maintained during the migration process. For example, if R1 was logically accessed before R2 before the migration, the corresponding entry for R1 in the updated slot list will still be located before R2. Maintaining the relative order facilitates subsequent batch reads and continuous organization of block table entries, reducing the additional processing required to restore the logical page order. However, for applications that rely entirely on equivalent locations... The attention implementation that determines positional relationships does not necessarily require the physical migration order to be consistent with the logical order, as long as the block table or related indexes can correctly restore the logical access order of the representative vectors.

[0103] When the representative vector uses equivalent position and cardinality to participate in attention calculation, the physical transfer itself does not change the value, equivalent position or cardinality of the representative vector. Therefore, from the perspective of attention calculation, the logical data set before and after the transfer remains unchanged.

[0104] Let the key corresponding to the representative vector be k_r, the value be v_r, the equivalent position be pos_r*, and the cardinality be card_r. Then, the contribution of the representative vector to the query q can be expressed as a function of these quantities, F(q, k_r, v_r, pos_r*, card_r). Cross-physical page block migration only changes the physical address of this data, without changing the content of (k_r, v_r, pos_r*, card_r). Therefore, under the condition that the block table is correctly updated and can continue to retrieve the same data, the attention results before and after migration remain consistent. Thus, the cross-block compaction process of this invention can be regarded as a semantically lossless physical storage reorganization, and the model accuracy loss mainly depends on the preceding key-value merging algorithm, rather than the physical relocation.

[0105] Let the query vector be q. A logical page, after merging, contains m representative vectors. The key of the r-th representative vector is... Value The base number is Since it represents a vector Approximately represents If the original key vectors are treated as a single entry during attention normalization, the weights of these original entries in the softmax denominator will be underestimated by approximately [percentage missing]. This results in an overall low attention weight. Therefore, in one implementation, the cardinality can be added to the attention score in logarithmic form, meaning the attention weight of vector r on query q is calculated using the following formula:

[0106]

[0107] Where d is the dimension of the key vector, and m is the number of representative vectors participating in the current attention calculation. The number of original key vectors aggregated by the s-th representative vector. Let be the key of the s-th representative vector.

[0108] The above equation is equivalent to dividing the attention score representing vector r by its cardinality. Weighted and then normalized, so that After the original key-value vectors are merged into a single representative vector, their total weight in the softmax denominator remains approximately the same as before the merging. For A single key-value vector with a value of 1, ln =0, the above formula degenerates into standard attention calculation. The contribution of the representative vector to the output is... Therefore, cardinality With representative vector , Strict pairing and reading are required. If an incorrect cardinality is read after cross-block migration, it will directly lead to incorrect attention weights. Therefore, this invention requires that metadata and representative vectors be migrated one-to-one according to the same slot index.

[0109] For large language models employing rotational positional encoding, the equivalent positions of representative vectors and fusion weights can be further optimized. In rotational positional encoding, two adjacent dimensions of a key vector typically form a two-dimensional rotation plane, and a corresponding rotation angle is applied according to the token position. If multiple key vectors at different positions are directly merged, and the two-dimensional components use inconsistent fusion methods, the original relative positional relationships may be disrupted. Therefore, in a preferred embodiment, consistent fusion weights are applied to key vector components that form the same two-dimensional rotation plane. In other words, for the same original key value entry, the two-dimensional vector composed of the 2j-th dimension and the 2j+1-th dimension uses the same fusion weight. To merge, that is:

[0110]

[0111] This ensures that the fusion operation remains consistent within the two-dimensional plane of rotation. To avoid notation confusion, we will use [the term "fusion operation" here]. This represents the overall weight of the j-th original key-value entry in the fusion, in order to and Let represent the fusion weights of the 2i-th and 2i+1-th dimensions of the entry, respectively. Then, the above consistency constraint can be written as: , where i is the index of the rotation plane. When this constraint is satisfied, the fused representative key vector in each two-dimensional rotation plane is equal to the linear combination of the two-dimensional components of each original key vector in that plane with the same weights. Its dot product with the query vector can still be expressed as the weighted sum of the rotation angles of each original relative position, thus maintaining consistency with the rotation angle corresponding to the equivalent position pos*, and avoiding the destruction of the relative position relationship of the rotation position encoding when different dimensional components use inconsistent weights.

[0112] In a further implementation, the subsequent merging intensity can be adjusted based on the actual number of physical blocks returned to the physical block allocator, such as... Figure 3 As shown, it specifically includes:

[0113] S301. Count the number of physical pages actually returned to the free block pool in this period. And obtain the currently occupied video memory from the physical page block allocator. ;

[0114] S302, according to With target memory deviation and Update the control parameter λ;

[0115] S303. Determine the merging strength for the next cycle based on the updated λ using a monotonically non-decreasing mapping, and provide it to the key-value vector merging module. The merging strength can be represented in various ways, such as the number of logical pages selected for merging in each processing cycle, the number of target representative vectors m in each logical page, the compression ratio n / m, the similarity clustering threshold, the proportion of key-value entries allowed to be merged, or other parameters that can affect the degree of key-value vector merging.

[0116] In a simple implementation, the target video memory amount can be set. And it calculates the current actual amount of video memory used from the physical page block allocator. .when Significantly higher When the actual resource pressure of the pagination key-value cache is high, the merging intensity can be increased; when a large number of physical pages are actually returned through compaction in this cycle, the current merging has effectively formed recyclable resources, and the intensity of subsequent merging can be appropriately reduced to avoid unnecessary information loss caused by continued compression.

[0117] To quantify the above relationship, a control parameter λ can be set, which characterizes the marginal cost or memory pressure per unit of video memory. A higher λ indicates that the system is more inclined to sacrifice some key-value precision in exchange for more video memory. As an example, λ can be updated using the following projective iterative method, where... Indicates projection onto the non-negative interval:

[0118]

[0119] in, For the control parameters of the current cycle, To update the step size, This represents the current actual amount of video memory used. For target memory size, This represents the actual amount of physical pages returned during this cycle. This is the feedback coefficient for recycling. To ensure consistency of dimensions in the updated formula, when and When measured in bytes, the amount of data reclaimed should be converted into the number of physical pages returned. The product of ζ and the number of bytes in a single physical page block, D_block, is... • D_block participates in the operation; when and When measured by the number of physical pages, it can be used directly. ζ is a dimensionless recovery feedback coefficient, which can take values ​​from 0.5 to 2.

[0120] Control parameters It can also be used as the dual variable corresponding to the Lagrangian function constructed based on memory capacity constraints:

[0121]

[0122] in, The cumulative information loss caused by the merger.

[0123] The update step size corresponding to the projection-based iterative update The depth of the concurrent request queue Q increases with the increase of the large language model inference. For example, it can be set to... ,in The update step size is based on the base value, where k is a non-negative coefficient. When the concurrent request queue is deep, more requests may need to allocate key-value cache space in the near future, so increasing the step size is appropriate. This allows the control parameter λ to respond more quickly to memory pressure, thus increasing the merging intensity earlier. Conversely, when the request queue is shallow, the adjustment speed can be reduced, prioritizing the system to maintain model accuracy. Q can also be replaced or expanded to load metrics such as the expected future token growth, the total length of waiting request contexts, and the current low watermark of free pages.

[0124] The updated control parameter λ is converted into a specific merge intensity through a preset monotonically non-decreasing mapping. In one implementation, the merge intensity is represented by the number of logical pages merged per processing cycle, N_merge, which can be set to min(N_max, / _ref×N_max), where N_max is the maximum number of logical pages allowed to be merged in a single cycle. _ref is a reference control parameter value, which can be taken as the system's steady-state operating value near the target memory level. Typical values; in another implementation, the merging strength is represented by the compression ratio per logical page r = n / m, which can be set to r = min(r_max, r_0 + κ × ... ), where r_0 is the base compression ratio, κ is the non-negative gain coefficient, and r_max is the maximum allowable compression ratio; it can also be... This is mapped to an adjustment amount for the similarity clustering threshold τ. The larger the value, the lower the value of τ, and the more key-value vectors are considered mergingable. All of the above mappings satisfy the condition that the merging strength increases with... The monotonic non-decreasing property ensures that the merging intensity increases when memory pressure rises or physical reclamation is insufficient, and decreases when the actual number of physical pages returned is sufficient. The initial value can be set to 0 or a small positive number, and its range can be limited to [0, ..., ... _max] within, _max corresponds to the maximum merge strength.

[0125] In another preferred embodiment, the utility density can be determined for each candidate logical page before performing the merge. And then according to With control parameters The relationships between logical pages are selected to be retained, merged, or evicted, thereby enabling the rapid merging of logical pages and the rapid release and reclamation of physical page blocks. The process is as follows: Figure 4 As shown. Utility density represents the degree to which the information value contained in a logical page is relative to its memory usage, that is, the compressibility of the candidate logical page. The more similar the key-value entries within a page, the higher the information redundancy and the lower the potential loss caused by merging. Therefore, the similarity of key vectors within a page can be used as one of the factors in calculating utility density.

[0126] For example, for containing The logical page p of a key vector can compute any two key vectors. and Similarity between (Cosine similarity can be used). A similarity threshold can be set. And statistically satisfy The proportion of vector pairs to all pairwise combinations is defined as redundancy. :

[0127]

[0128] When the ratio of similar vector pairs is high Relatively large.

[0129] In one example, utility density can be further defined as:

[0130]

[0131] in, This indicates the video memory resources occupied by logical page p, or the normalized video memory usage.

[0132] Thus, when the vectors within the same page are highly similar, Approaching 1, The lower the value, the more suitable the page is for merging; when the vector differences within the page are large, Higher, more inclined to retain.

[0133] A tolerance parameter ε can be set with λ as the center, forming two thresholds, namely the first threshold ( ) / second threshold ( ).when When the logical page information is of high value, all key-value entries on that page can be retained; when... At this time, a merge can be performed on the logical page, converting multiple key-value entries into a smaller representative vector; when If this occurs, it indicates that the logical page has high redundancy or low value per unit of memory, and the key-value data in the logical page can be directly evicted if the upper-level key-value caching strategy allows. The ternary decision-making method can provide a smoother compression method for logical pages whose information value is in the middle range than the binary "keep" / "delete" method.

[0134] Figure 4 The ternary decision-making process shown includes:

[0135] S401. Calculate the utility density for candidate logical pages. ;

[0136] S402, will With the first threshold ( ) Comparison, if Then the logical page is retained;

[0137] S403, otherwise With the second threshold ( ) Comparison, if Then the logical page will be merged;

[0138] S404, if Then, the logical page is discarded and its occupied slot is updated to an idle state; the process ends after the above judgment is completed.

[0139] If both eviction and merging operations occur simultaneously within the same processing cycle, it is preferable to perform full-page eviction first, followed by cross-block compaction based on merging holes. For example, if a logical page needs to be evicted based on its utility density, all of its slots can be directly made free. If this logical page occupies a physical page block exclusively, a complete free physical page block can be directly generated without any representative vector migration; if some of its data shares a physical page block with other logical pages, the number of free slots in that page block can be increased at least. Therefore, by performing eviction first and updating the slot occupancy status of each physical page block, and then recalculating the cross-block migration scheme, more free slots can be obtained for migration, reducing subsequent migration costs.

[0140] Conversely, if cross-block compaction is performed first, some representative vectors may be migrated to a physical page block that is subsequently evicted entirely, resulting in invalid migrations. Therefore, the preferred order of "evicting and updating slot occupancy status first, then determining the migration plan" can avoid unnecessary data copying and improve the execution efficiency of the entire key-value cache management cycle.

[0141] When performing large-scale cross-block migrations, memory reads and writes can incur bandwidth overhead. Therefore, representative vector migration, metadata migration, and block table updates can be integrated into one or a small number of GPU cores. In a preferred embodiment, the representative vector, corresponding metadata, and related block table entries from the physical page blocks to be migrated are loaded into the GPU's on-chip storage, such as shared memory, registers, or other low-latency storage areas, on a tile-by-tile basis. Subsequently, the target block_id and slot_idx corresponding to each representative vector are determined on-chip based on the free_slot_bitmap, and the updated block table entries and the new slot states of the source and target page blocks are constructed. Finally, the representative vector, metadata, and updated block table entries are written back to the video memory.

[0142] For example, when `block_size=16`, one warp or one thread block can handle one or more physical page blocks. Threads can read the `free_slot_bitmap` in parallel and use bitwise operations such as `popcount` and `find-first-set` to quickly obtain free slot indices. For multiple representative vectors to be migrated, target free slots can be allocated to each representative vector through prefix sum calculations. Block table entries can also be pre-generated in the same kernel and committed uniformly after data write-back is complete. Using operator fusion reduces the number of times intermediate results are repeatedly written back and re-read from memory, and reduces startup overhead between multiple GPU cores.

[0143] "Loading to on-chip storage" does not necessarily mean loading the entire physical page block of data at once. If the representative vector size is large and cannot be fully accommodated in shared memory, it can be migrated tile by tile according to vector dimension, attention head, or layer. For example, the target address mapping can be determined first, and then the key data, value data, and metadata can be moved sequentially across multiple tiles. As long as the representative vector, metadata, and mapping relationship are consistently updated overall, it falls under the fusion and compaction implementation described in this invention.

[0144] This invention uses the actual number of physical page blocks returned to the physical page block allocator as the primary metric for physical reclamation effectiveness. The paging key-value cache system contains multiple levels of "video memory usage." Device-level video memory may have already been allocated by the key-value cache pool when the inference service starts. Even if physical page blocks are subsequently reclaimed, the total video memory usage displayed by the device driver may not immediately decrease. However, after physical page blocks are returned to the free block pool, they can be reused by other inference requests, thus the resource pressure within the paging pool has actually decreased.

[0145] Based on this characteristic, metrics such as the number of returned blocks, pool occupancy, and migration overhead can be simultaneously calculated. The number of returned blocks represents the number of physical pages actually returned to the free block pool per unit period; the pool occupancy rate represents the ratio between the currently allocated physical pages and the total number of physical pages in the paging cache pool; migration overhead can represent the proportion of vector copying times, copied bytes, or compaction time to total decoding time. Logical compression ratio can still be used as an algorithm-level metric, but it is no longer the sole criterion for successful memory reclamation. Using the actual number of returned physical pages for evaluation more directly reflects the extent to which this invention improves inference concurrency and key-value cache allocable capacity.

[0146] This invention can also be implemented as a paginated key-value cache cross-page block compaction and page block reclamation feedback adjustment device. The device can operate as a key-value cache management subsystem within a large language model inference framework, or it can be implemented jointly by multiple software modules, GPU kernels, and a physical page block allocator. (Reference) Figure 5 The device may include at least a migration scheme determination module 10, a cross-block compaction execution module 20, a mapping update module 30, a physical recycling module 40, and a feedback adjustment module 50, each of which executes the aforementioned steps S1 to S5 respectively.

[0147] The migration scheme determination module is used to determine a migration scheme that can make all slots of one or more physical page blocks free after merging multiple key-value vectors in at least one logical page, based on the slot occupancy status of each physical page block. The migration scheme determination module can run on either the CPU or the GPU. If the number of physical page blocks is small or the compaction cycle is long, the CPU can perform sorting, benefit assessment, and target page selection; if compaction needs to be performed at a higher frequency, migration planning can be completed on the GPU using parallel scanning, bucketing statistics, or prefix sums.

[0148] The cross-block compaction execution module migrates the representative vectors and corresponding metadata from the physical page blocks to be migrated out to free slots in other physical page blocks according to the migration scheme. This module can be implemented by a GPU copy kernel or a custom CUDA / Triton kernel integrated into the attention service framework. The mapping update module updates the slot-level block table according to the new physical location of the representative vectors, enabling subsequent attention kernels to continue accessing the correct representative vectors and their metadata. The physical reclamation module calls the allocator interface after confirming that a physical page block is completely empty, and adds the physical page block back to the free block pool.

[0149] The feedback adjustment module counts the actual number of physical pages returned in the current cycle and adjusts the subsequent merging intensity based on the current physical memory pressure. The feedback adjustment module can communicate with the existing request scheduler to obtain the number of queued requests, the number of tokens to be processed, or future key-value cache demand predictions, and provide the updated merging control parameters to the key-value vector merging module. In this way, the physical reclamation status can influence the logical compression strategy in reverse, forming a closed loop rather than operating independently.

[0150] The aforementioned modules do not necessarily correspond to independent hardware units. For example, the migration scheme determination module and the feedback adjustment module can be software programs running on the main processor; the cross-block compaction execution module and the mapping update module can be integrated into a GPU core; and the physical reclamation module can call the interface of the physical page block manager in an existing inference framework. As long as the corresponding functions are implemented, it can be considered to constitute the apparatus described in this invention.

[0151] The method of this invention can also be implemented by a computer program. The computer program can be stored in non-volatile memory, solid-state drive, memory card, read-only memory, or other computer-readable storage media. When the processor executes the program, it can perform operations such as slot status maintenance, migration scheme determination, representative vector and metadata migration, block table update, physical page block reclamation, and merge intensity feedback adjustment. The processor may include a CPU, GPU, NPU, or a combination of the above processors.

[0152] Through the above implementation, this invention establishes a direct link between the logical compression process of key-value caching and the paged physical memory reclamation process. After reducing the number of logically valid key-value entries through key-value vector merging, the system no longer simply retains scattered empty slots as unusable fragments in the original physical page blocks. Instead, it determines a migration scheme that can generate complete free page blocks based on the physical page block occupancy status. By moving representative vectors and their metadata across physical page blocks, it aggregates scattered free slots within multiple physical page blocks into a few source physical page blocks, making all these source physical page blocks empty and returning them to the allocator. Thus, the space savings generated by logical compression can be reflected in the form of reallocatable physical page blocks.

[0153] Prioritizing low-occupancy physical page blocks as outgoing pages reduces the number of valid representative vectors needed to free up a single physical page block; prioritizing target physical page blocks with high suitability reduces fragmentation regenerated during the compaction process; assessing migration costs and recovery benefits reduces ineffective migrations; migrating and remapping slot-level block tables based on a one-to-one correspondence between representative vectors and metadata using the same slot index maintains the semantics of attention computation before and after physical migration, making cross-block compaction a semantically lossless physical organization process in merging scenarios; treating single key-value vectors with a cardinality of 1 as migration objects on an equal footing with merged representative vectors ensures that all physical page blocks to be migrated out are indeed empty after migration; and determining compatibility conditions and binning feasibility for incoming page blocks avoids cross-request, cross-layer, and cross-processing issues. Cross-head group misalignment and feasibility misjudgment; executing in the order of "write target first, then update mapping, and finally release source slots" can improve data consistency during migration; adjusting the subsequent merging intensity based on the actual number of returned physical pages can create a feedback loop between logical compression control and the actual physical memory state; dynamically adjusting the control step size based on the request queue depth can improve the system's responsiveness to future memory pressure; adopting a ternary decision of retention, merging, and eviction can achieve smoother scheduling between memory saving and model information preservation; by using equivalent position and fusion weight constraints under rotational position encoding, the applicability of the merged representative vector in position-related attention calculation can be improved; by using on-chip storage and operator fusion, the memory access overhead caused by cross-block compaction itself can be reduced.

[0154] Therefore, this invention can form a complete technical closed loop under the paginated key-value caching architecture, from logical merging and compression to actual physical page block reclamation and then to adjusting logical compression based on feedback from the actual reclamation results. This improves the reusability of physical page blocks within the paginated cache pool, alleviates the pressure on GPU memory resources in long context and high-concurrency inference scenarios, and improves the deployability of key-value caching compression technology in actual paginated inference systems while ensuring the semantic correctness of the merged representative vector access.

[0155] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions and improvements made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A method for adjusting cross-page block compaction and page block reclamation feedback in pagination key-value caching, characterized in that, Includes the following steps: After merging multiple original key-value vectors in at least one logical page, a migration scheme is determined based on the slot occupancy status of each physical page block to make all slots of at least one physical page block free through cross-physical page block migration. The migration scheme indicates the physical page block to be migrated out and other physical page blocks for receiving representative vectors from the physical page block to be migrated out. The other physical page blocks are physical page blocks that belong to the same inference request, the same network layer, and the same attention head group as the physical page block to be migrated out, and are not shared by multiple logical pages. According to the migration scheme, all valid representative vectors in the physical page block to be migrated out are migrated to the free slots of the other physical page blocks, and the metadata corresponding to each representative vector is migrated synchronously with the representative vector, so that all slots in the physical page block to be migrated out become free; wherein, the representative vector includes a merged representative vector obtained by merging multiple key-value vectors and a single key-value vector that did not participate in the merging and has a cardinality of 1, and the metadata includes at least the equivalent position used to characterize the comprehensive position of the multiple original key-value vectors that participated in generating the representative vector in the sense of position encoding and the cardinality used to characterize the number of the original key-value vectors, and the metadata and the representative vector are stored with the same physical page block identifier and slot index; The slot-level mapping of the corresponding logical page in the block table is updated according to the physical page block identifier and slot index where the representative vector is located after migration. The block table records the physical page block identifier and slot index where each representative vector contained in each logical page is located. After the block table update is completed, all physical page blocks to be migrated out with all slots in an idle state are returned to the idle block pool of the physical page block allocator; and The number of physical pages actually returned to the free block pool is counted, and the merging strength of subsequent merging of pagination key-value cache is adjusted based on the number of physical pages actually returned rather than the logical compression rate, so that the above key-value vector merging, cross-physical page migration and physical page return form a closed loop with the merging strength.

2. The method according to claim 1, characterized in that, The slot occupancy status of each physical page block includes the number of occupied slots of the physical page block and a free slot bitmap used to indicate whether each slot is free. The slot occupancy status is incrementally updated in an event-driven manner during key-value vector merging, representative vector migration, new key-value vector writing, and physical page block return.

3. The method according to claim 1, characterized in that, The determination of a migration scheme capable of making all slots in at least one physical page block idle through cross-physical page block migration includes: Candidate physical pages to be migrated out are selected in ascending order of the number of occupied slots in each physical page block; The number of representative vectors to be migrated in the candidate physical page blocks to be migrated is accumulated, and the number of free slots that each physical page block can provide in the remaining physical page blocks other than the candidate physical page blocks to be migrated is determined. When the packing conditions are met, the candidate physical pages to be migrated out are identified as physical pages that can be completely emptied. The number of candidate physical pages to be migrated out is gradually increased until the packing conditions are no longer met, resulting in the number of physical pages that can be completely emptied. The packing conditions include: the total number of free slots that the remaining physical pages can provide is not less than the number of representative vectors to be migrated, and the representative vectors to be migrated in each candidate physical page to be migrated out can be allocated to one or more of the remaining physical pages with a sufficient number of free slots to accommodate the allocated representative vectors.

4. The method according to claim 1, characterized in that, Before executing the migration scheme, the following is also included: The migration cost is determined based on the number of representative vectors that need to be migrated according to the migration scheme and the amount of data for each representative vector along with its metadata. The recovery benefit is determined based on the number of physical pages that can be completely vacated according to the migration scheme and the cache capacity of a single physical page. The migration scheme is executed only when the migration cost and the recovery benefit meet a preset cost-benefit condition; the preset cost-benefit condition is that the number of representative vectors to be migrated is not greater than the product of the cost-benefit coefficient, the number of physical pages that can be completely vacated, and the number of slots in a single physical page.

5. The method according to claim 1, characterized in that, The determination of a migration scheme that can make all slots of at least one physical page block free through cross-physical page block migration also includes: Prioritize physical pages with fewer occupied slots as the physical pages to be migrated out; and For a representative vector to be migrated, among physical page blocks with enough free slots to accommodate the representative vector to be migrated, the physical page block with the fewest remaining free slots after accommodating the vector is preferentially selected as the migration-in physical page block, and representative vectors belonging to the same physical page block to be migrated out are preferentially migrated into the same migration-in physical page block.

6. The method according to claim 1, characterized in that, The adjustment of the merging intensity includes: The video memory pressure is determined based on the difference between the currently used video memory and the target video memory. Based on the memory pressure and the actual number of physical pages returned, iteratively update the control parameters characterizing the marginal cost per unit of memory resource; and Based on the updated control parameters, the number of logical pages and / or the merging ratio to be subsequently performed are determined according to a preset monotonically non-decreasing mapping. The control parameter is used to characterize the marginal information loss cost per unit of video memory resource. Its update amount is equal to the product of the update step size and the pressure term and projected onto the non-negative interval. The pressure term is the video memory pressure minus the product of the recovery feedback coefficient and the amount of video memory recovered corresponding to the actual number of physical pages returned. The video memory pressure and the amount of video memory recovered use the same dimension. The number of logical pages and / or the merging ratio subsequently executed are monotonically non-decreasing with the control parameter.

7. The method according to claim 6, characterized in that, Prior to performing the merge, the following is also included: The utility density is determined for candidate logical pages. The utility density is determined based on the redundancy represented by the proportion of vector pairs whose similarity between key vectors in the candidate logical page is higher than a similarity threshold, and the amount of video memory occupied by the candidate logical page. The higher the redundancy, the lower the utility density. A tolerance parameter is set with the control parameter as the center to obtain a first threshold higher than the control parameter and a second threshold lower than the control parameter, and the utility density is compared with the first threshold and the second threshold. When the utility density is higher than the first threshold, all key-value vectors in the candidate logical page are retained; When the utility density is between the second threshold and the first threshold, merging of the candidate logical pages is performed; and When the utility density is lower than the second threshold, all key-value vectors in the candidate logical page are eliminated and their occupied slots are updated to an idle state; wherein, within the same processing cycle, the elimination is performed first and the slot occupancy status of each physical page block is updated, and then the migration scheme is determined.

8. The method according to claim 1, characterized in that, The method is applied to a large language model using rotational position encoding. The merging includes: for key vectors belonging to the same attention head but located at different positions among the multiple key-value vectors, their two-dimensional vector components in the two-dimensional rotational plane of rotational position encoding are merged using consistent fusion weights, so that the rotation angle of the fused representative vector in the two-dimensional rotational plane is consistent with the equivalent position.

9. A pagination key-value cache cross-page block compaction and page block reclamation feedback adjustment device, characterized in that, include: The migration scheme determination module is used to determine, after merging multiple key-value vectors in at least one logical page, a migration scheme that can make all slots of at least one physical page block free through cross-physical page block migration, based on the slot occupancy status of each physical page block; wherein, the migration scheme indicates the physical page block to be migrated out and other physical page blocks for receiving representative vectors in the physical page block to be migrated out, wherein the other physical page blocks are physical page blocks that belong to the same inference request, the same network layer and the same attention head group as the physical page block to be migrated out, and are not shared by multiple logical pages. The cross-block compaction execution module is used to migrate all valid representative vectors in the physical page block to be migrated out to the free slots of other physical page blocks according to the migration scheme, and to migrate the metadata corresponding to each representative vector synchronously with the representative vector, so that all slots in the physical page block to be migrated out become free; wherein, the representative vector includes a merged representative vector obtained by merging multiple key-value vectors and a single key-value vector that did not participate in the merging and has a cardinality of 1, and the metadata includes at least the equivalent position used to characterize the comprehensive position of the multiple original key-value vectors participating in the generation of the representative vector in the sense of position encoding and the cardinality used to characterize the number of the original key-value vectors; The mapping update module is used to update the slot-level mapping of the corresponding logical page in the block table according to the physical page block identifier and slot index where the representative vector is located after migration. The block table records the physical page block identifier and slot index where each representative vector contained in each logical page is located. The physical recycling module is used to return physical page blocks with zero occupied slots and a free slot bitmap indicating all slots are free to the free block pool of the physical page block allocator after the block table update is completed; and The feedback adjustment module is used to count the number of physical page blocks actually returned to the free block pool during the current compaction cycle, and update the control parameters that characterize the marginal cost of unit video memory resources based on the number of physical page blocks actually returned and the deviation of the current occupied video memory amount relative to the target video memory amount. Then, based on the updated control parameters, the module adjusts the number of logical pages and / or the merging ratio for subsequent merging of paging key-value cache.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the steps of the paging key-value cache cross-page block compaction and page block reclamation feedback adjustment method as described in any one of claims 1 to 8.