Efficient sparse attention algorithm optimization method and device, equipment and medium

By introducing optimization methods such as layernorm based on importance perception, row-directional product sparse matrix multiplication and group hash multiplication, and softmax calculation based on shift operation in the attention algorithm, the attention algorithm is solved on the edge device. The calculation resource consumption and efficiency issues have achieved the effect of significantly improving the efficiency of attention algorithms.

CN119476360AActive Publication Date: 2025-02-18SOUTH CHINA UNIV OF TECH +1

Patent Information

Application Number
CN202411402325.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-10-09
Publication Date
2025-02-18
Estimated Expiration
2044-10-09

AI Technical Summary

Technical Problem

When the attention algorithm calculates the importance of each element in the input sequence in a sequence model, it requires a large amount of computing resources, resulting in the standard attention mechanism having a quadratic time complexity, making it difficult to deploy and efficient inference on edge devices.

Method used

By obtaining the pending data and performing layernorm calculation based on importance perception, the normalized data is obtained; then the normalized data is multiplied by row-directional product sparse matrix and grouped hash multiplication to obtain the attention score matrix; then the normalized data is obtained by multiplication of row-directional product sparse matrix and grouped hash hash multiplication to obtain the attention score matrix; According to the attention fraction matrix, softmax calculation based on shift operation is performed to obtain the softmax calculation result; finally, row-direction product sparse matrix multiplication is performed on the softmax calculation result and the median vector of the attention force matrix to obtain the attention calculation result.

Benefits of technology

The sparse attention algorithm is optimized through improved layernorm, softmax and matrix multiplication, reducing the amount of data during the attention algorithm processing process, significantly improving the efficiency of the attention algorithm.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119476360A_ABST
    Figure CN119476360A_ABST
Patent Text Reader

Abstract

The invention relates to an efficient sparse attention algorithm optimization method and device, equipment and a medium, and the method comprises the steps: obtaining to-be-processed data, and carrying out the layernorm calculation of the to-be-processed data based on importance perception, and obtaining the normalized data; performing row product sparse matrix multiplication and packet hash multi-head attention processing on the normalized data to obtain an attention score matrix; performing softmax calculation based on shift operation according to the attention score matrix to obtain a softmax calculation result; and performing row product sparse matrix multiplication on the softmax calculation result and the attention matrix median vector to obtain an attention calculation result. In the whole process, the sparse attention algorithm is optimized through improved layernorm, softmax and matrix multiplication, the data volume in the attention algorithm processing process is reduced, and the efficiency of the attention algorithm can be remarkably improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present application relates to the field of computer technology, and in particular to an efficient sparse attention algorithm optimization method, apparatus, computer equipment, storage medium and computer program product. Background Art

[0002] The attention algorithm is a mechanism for calculating the importance of each element in the input sequence in a sequence model. The attention algorithm allows the model to dynamically focus on different parts of the sequence when processing sequence data. The core idea is to calculate a weight, namely the attention score, at each position in the sequence. This weight represents the importance of the position in the current context.

[0003] However, attention algorithms require a lot of computing resources. The standard attention mechanism has quadratic time complexity and requires considerable storage and computational overhead, making its deployment and efficient inference on edge devices challenging.

[0004] It can be seen that there is an urgent need for an effective attention algorithm optimization solution to significantly improve the efficiency of the attention algorithm. Summary of the invention

[0005] Based on this, it is necessary to provide an efficient sparse attention algorithm optimization method, device, computer equipment, storage medium and computer program product that can significantly improve the efficiency of the attention algorithm in response to the above technical problems.

[0006] In a first aspect, the present application provides an efficient sparse attention algorithm optimization method. The method comprises:

[0007] Acquire the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0008] Performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0009] Performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0010] Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0011] In one embodiment, the step of obtaining the data to be processed and performing layernorm calculation based on importance perception on the data to be processed to obtain normalized data includes:

[0012] Get the data to be processed;

[0013] Calculating the absolute value of each element in the data to be processed;

[0014] The elements with a preset percentage before the absolute value are retained, and the remaining elements are set to zero to obtain the adjusted data;

[0015] Perform layernorm calculation on the adjusted data to obtain normalized data.

[0016] In one embodiment, performing layernorm calculation on the adjusted data to obtain normalized data includes:

[0017] Identifying non-zero elements in the adjusted data, and calculating the square of the non-zero elements;

[0018] If the square of the current non-zero element is less than the preset first threshold, the current non-zero element is set to zero;

[0019] Accumulate the element values ​​and square values ​​of the adjusted non-zero elements;

[0020] According to the element value and the square value, the layernorm output result of each element normalization is obtained.

[0021] In one embodiment, performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix includes:

[0022] Applying a linear transformation to the normalized data to obtain a query vector, a key vector, and a value vector;

[0023] Performing CSR compression on the query vector, key vector and value vector;

[0024] Calculate a dot product matrix of query and key based on the query vector and the key vector;

[0025] Hash grouping is performed on the dot product matrix, and row-wise sparse matrix multiplication is performed on the query vector and the key vector in each hash group, and the results are accumulated to obtain a row of the output matrix;

[0026] Output rearranges each row of the output matrix to obtain an attention score matrix.

[0027] In one embodiment, performing hash grouping on the dot product matrix includes:

[0028] Hashing the non-zero query vectors and key vectors in the dot product matrix multiple times;

[0029] The query vector and the key vector are assigned to different hash groups without duplication.

[0030] In one embodiment, performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result includes:

[0031] Dividing the attention score matrix into a plurality of groups;

[0032] Find the maximum value in each group and obtain a preset second threshold, where the preset second threshold is determined based on the overall tensor corresponding to all data in the group;

[0033] Calculate the difference between each element in the group and the maximum value in the group, and if the difference is greater than the preset second threshold, set the corresponding element to zero;

[0034] Calculate the difference value to a power with 2 as the exponent base to obtain an intermediate result;

[0035] Find the maximum value among all elements based on the maximum values ​​in different groups;

[0036] The intermediate result is compensated by the maximum value of all the elements, and the softmax calculation is completed by a shift operation to obtain a softmax calculation result.

[0037] In one embodiment, dividing the attention score matrix into a plurality of groups comprises:

[0038] Scaling the attention score matrix by dividing it by the dimension of the key matrix to obtain a scaled attention score matrix;

[0039] The scaled attention score matrix is ​​divided into several groups.

[0040] In a second aspect, the present application also provides an efficient sparse attention algorithm optimization device. The device comprises:

[0041] A normalization module, used for acquiring data to be processed, and performing layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0042] An attention processing module, used for performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0043] A softmax calculation module, used for performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0044] The attention calculation module is used to perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0045] In a third aspect, the present application further provides a computer device. The computer device includes a memory and a processor, the memory stores a computer program, and the processor implements the following steps when executing the computer program:

[0046] Acquire the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0047] Performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0048] Performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0049] Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0050] In a fourth aspect, the present application further provides a computer-readable storage medium. The computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the following steps are implemented:

[0051] Acquire the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0052] Performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0053] Performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0054] Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0055] In a fifth aspect, the present application further provides a computer program product. The computer program product includes a computer program, and when the computer program is executed by a processor, the following steps are implemented:

[0056] Acquire the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0057] Performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0058] Performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0059] Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0060] The above-mentioned efficient sparse attention algorithm optimization method, device, computer equipment, storage medium and computer program product obtain the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data; perform row-wise product sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix; perform softmax calculation based on shift operation according to the attention score matrix to obtain the softmax calculation result; perform row-wise product sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result. In the whole process, the sparse attention algorithm is optimized through improved layernorm, softmax, and matrix multiplication, and the amount of data in the attention algorithm processing process is reduced, which can significantly improve the efficiency of the attention algorithm. BRIEF DESCRIPTION OF THE DRAWINGS

[0061] Figure 1 An application environment diagram of an efficient sparse attention algorithm optimization method in one embodiment;

[0062] Figure 2 A flowchart of an efficient sparse attention algorithm optimization method in one embodiment;

[0063] Figure 3 A schematic diagram of a flow chart of an efficient sparse attention algorithm optimization method in another embodiment;

[0064] Figure 4 A structural block diagram of an efficient sparse attention algorithm optimization device in one embodiment;

[0065] Figure 5 FIG. 4 is a diagram showing the internal structure of a computer device in one embodiment. DETAILED DESCRIPTION

[0066] In order to make the purpose, technical solution and advantages of the present application more clearly understood, the present application is further described in detail below in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are only used to explain the present application and are not used to limit the present application.

[0067] The efficient sparse attention algorithm optimization method provided in the embodiment of the present application can be applied to Figure 1In the application environment shown. Among them, the terminal 102 communicates with the server 104 through the network. The data storage system can store the data that the server 104 needs to process. The data storage system can be integrated on the server 104, or it can be placed on the cloud or other network servers. The terminal 102 sends an attention algorithm optimization request to the server 104, and the server 104 is pre-loaded with the original attention algorithm. The server 104 responds to the attention algorithm optimization request, obtains the data to be processed, and performs layernorm calculation based on importance perception on the data to be processed to obtain normalized data; performs row-wise product sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix; performs softmax calculation based on shift operation according to the attention score matrix to obtain a softmax calculation result; performs row-wise product sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain an attention calculation result. Among them, the terminal 102 can be, but is not limited to, various personal computers, laptops, smart phones, tablets, Internet of Things devices and portable wearable devices. The Internet of Things devices can be smart speakers, smart TVs, smart air conditioners, smart car-mounted devices, etc. The portable wearable device may be a smart watch, a smart bracelet, a head-mounted device, etc. The server 104 may be implemented as an independent server or a server cluster consisting of multiple servers.

[0068] In one embodiment, Figure 2 As shown in the figure, an efficient sparse attention algorithm optimization method is provided, which can be applied to Figure 1 Taking the server 104 in the example as an example, the following steps are included:

[0069] S200: Obtain the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data.

[0070] The data to be processed is usually sequence data, such as text, time series, etc., represented in the form of tensors. Before LayerNorm, the weights of different elements can be determined according to certain characteristics of the data (such as position, contextual relevance, etc.), thereby guiding LayerNorm to pay more attention to important elements. Specifically, the absolute value of each element in the data to be processed can be calculated to determine its importance, and then the data can be screened based on the importance, and a part of the data with the highest importance can be selected for layernorm calculation to obtain normalized data. Layernorm specifically refers to layer normalization of input data, which helps to speed up the training process and improve model stability. Importance-aware LayerNorm can introduce importance weights by modifying the calculation method of the mean and variance in the normalization process.

[0071] S400: Perform row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix.

[0072] Row-wise product sparse matrix multiplication: In the attention mechanism, it usually involves multiplication between a large key-value matrix and a query matrix. Sparse matrix multiplication reduces the amount of computation by only calculating important pairs of elements or those with large expected contributions. Row-wise product is a specific form of matrix multiplication in which the calculation of each row can be performed independently. Grouped hash multi-head attention: This is a variant of the multi-head attention mechanism, in which memory usage and computational complexity are reduced by grouping the input data and using a hash function to map the elements of each group to different "heads". Each head calculates the attention score independently, and then these scores are merged to generate the final attention output. After the above processing, the attention score matrix is ​​obtained.

[0073] S600: Perform a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result.

[0074] Softmax is usually used to convert attention scores into probability distributions, but in large-scale data, standard Softmax calculations are generally very time-consuming. In view of the time-consuming defects of traditional Softmax calculations, a shift operation is performed here to significantly reduce the amount of data processing and improve processing efficiency. Specifically, by utilizing the properties of the softmax function (such as maximum value translation invariance), the calculation can be simplified by first finding the maximum value in the score vector and then shifting all scores accordingly (i.e. subtracting the maximum value). Then, the shifted scores can be used for efficient exp and sum operations, and finally the probability distribution can be restored through a single division.

[0075] S800: Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0076] Perform matrix multiplication of the softmax calculation result (i.e., attention weight) with the value vector in the attention matrix to obtain the final attention calculation result. Since both the softmax result and the value vector may be sparse, sparse matrix multiplication can be used to speed up the calculation.

[0077] The above-mentioned efficient sparse attention algorithm optimization method obtains the data to be processed, and performs layernorm calculation based on importance perception on the data to be processed to obtain normalized data; performs row-wise product sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain the attention score matrix; performs softmax calculation based on shift operation according to the attention score matrix to obtain the softmax calculation result; performs row-wise product sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result. In the whole process, the sparse attention algorithm is optimized through improved layernorm, softmax, and matrix multiplication to reduce the amount of data in the attention algorithm processing process, which can significantly improve the efficiency of the attention algorithm.

[0078] In practical applications, suppose there is a text processing task and the input is a sequence of word IDs. At this time, the attention representation of this sequence needs to be calculated. The specific processing process of applying the efficient sparse attention algorithm optimization method of this application is as follows:

[0079] 1. Data preprocessing: Convert word IDs into embedding vectors and apply position-based importance-aware LayerNorm.

[0080] 2. Sparse Multi-Head Attention: Split the embedding vector into multiple heads; Use a hash function to assign different keys and values ​​to each head; Perform sparse matrix multiplication on each head to calculate the dot product between the query and the key to get the attention score; Combine the scores and apply the grouped hash multi-head attention mechanism.

[0081] 3. Softmax based on shift operation; perform maximum shift on the attention scores of each head; apply exp and sum operations, and then divide by the sum to get the probability distribution.

[0082] 4. Result calculation: Perform sparse matrix multiplication on the softmax result (attention weight) and the corresponding value vector. Combine the outputs of all heads to get the final attention calculation result.

[0083] like Figure 3 As shown, in one embodiment, S200 includes:

[0084] S220: Obtain data to be processed.

[0085] The data to be processed is usually sequence data, such as text, time series, etc., represented in the form of tensors.

[0086] S240: Calculate the absolute value of each element in the data to be processed.

[0087] In order to evaluate the importance of each element, the absolute value of each element is first calculated. The size of the absolute value can be regarded as a simple measure of the "importance" of the element.

[0088] S260: retaining the elements with a preset percentage before the absolute value and setting the remaining elements to zero, to obtain adjusted data.

[0089] Sort the elements by their absolute values, and keep the elements with the largest absolute values ​​in the first preset percentage (such as the first 10%, 20%, 30%, etc.), while setting the values ​​of other elements to zero. The purpose of this step is to highlight those "important" elements while ignoring those relatively unimportant elements. It should be noted that the "importance" here is defined based on the absolute value size, which may not fully reflect the actual importance of the element in the data.

[0090] S280: Perform layernorm calculation on the adjusted data to obtain normalized data.

[0091] Finally, LayerNorm is calculated for the adjusted data. LayerNorm usually normalizes each sample (or each element in the "layer") to have zero mean and unit variance (or adjust as needed). Since the data has been adjusted according to the importance of the elements, the normalization in this step will focus more on the important elements that are retained.

[0092] Furthermore, performing layernorm calculation on the adjusted data to obtain normalized data includes: identifying non-zero elements in the adjusted data, and calculating the square of the non-zero elements; if the square of the current non-zero element is less than a preset first threshold, setting the current non-zero element to zero; accumulating the element value and square value of the adjusted non-zero elements; and obtaining the normalized layernorm output result of each element according to the element value and the square value.

[0093] In a specific application example, the entire layernorm calculation process includes the following steps:

[0094] 1. After inputting the data, calculate the absolute value of each element, retain the first 20% of the data, and set the remaining data to zero to skip subsequent calculations. The sparsity here can be adjusted according to the data distribution.

[0095] 2. Calculate the square size x of each non-zero element 2 (After the data is squared, the differences in elements increase. In the subsequent normalization operation, only a few data contribute significantly to the result.) If the square value of an element is less than the threshold, the element is set to zero and the calculation of subsequent steps is skipped.

[0096] 3. Accumulate the values ​​of all input elements and calculate Ex.

[0097] 4. Add the square values ​​of the non-zero elements and calculate E(x 2 ).

[0098] 5. When all elements are calculated, Ex and E(x 2 ) output, the layernorm output result of each element normalization is obtained.

[0099] In one embodiment, row-wise sparse matrix multiplication and grouped hash multi-head attention processing are performed on the normalized data to obtain an attention score matrix including:

[0100] Step 1: Apply linear transformation on the normalized data to obtain query vector, key vector, and value vector.

[0101] The normalized data (usually an embedded representation of sequence data) is transformed into three different spaces to generate query, key, and value vectors. This is a standard step in the multi-head attention mechanism. The normalized data is transformed using different linear layers (usually fully connected layers), each with different weights and biases. Specifically, the attention matrix is ​​obtained directly after applying the linear transformation here.

[0102] Step 2: Perform CSR compression on the query vector, key vector, and value vector.

[0103] Perform CSR compression on the attention matrix containing the query vector, key vector and value vector. Specifically, the entire CSR compression process includes: 1) Represent each element in the matrix with a two-tuple (value, column number) and a row offset (different from the triple storage of COO), the value refers to the non-zero value in the matrix, the column number refers to the column where the non-zero value is located, and the row offset indicates the starting offset position of the first element of a row in the value group. 2) First fill the non-zero value of the first row element into the value group, and at the same time fill in the corresponding column number of the non-zero value in the column number group; fill in the starting offset position of the first element of each row in the value group in the row offset group, and fill in the total number of elements in the matrix at the end of the row offset.

[0104] Step 3: Based on the query vector and the key vector, calculate the dot product matrix of the query and the key.

[0105] The similarity between the query vector and the key vector is evaluated by calculating the dot product between them, which is the basis of the attention score; for each query vector, it is dot-producted with all key vectors to generate a dot product matrix.

[0106] Step 4: Hash the dot product matrix and perform row-wise sparse matrix multiplication on the query vector and key vector in each hash group, and accumulate them to obtain a row of the output matrix.

[0107] The query and key vectors are grouped together by hash grouping to reduce the amount of computation, and sparse matrix multiplication is performed within each hash group to approximate the calculation of the attention score. A hash function is applied to the index (or some hashable identifier) ​​of each query and key vector to assign them to different groups. Within each hash group, only the dot product of the query vector and the key vector within the group is calculated, and sparse matrix multiplication is used (if the data is sparse) to reduce unnecessary calculations. The calculation results of each hash group are accumulated (or merged) to form a row (or part) of the attention score matrix.

[0108] In practical applications, the specific process of the entire row-wise product sparse matrix multiplication is as follows: 1) Create an array of length n according to the number of columns n of the output matrix. 2) According to the row offset of the left multiplication matrix CSR, take out all elements of the first row from the tuple of numerical value and column number, and then take out each row element of the corresponding column number of the right multiplication matrix according to the first column number. 3) Multiply the column number value of the left multiplication element with a row of the corresponding right multiplication element, and store the corresponding value in the array. 4) When all non-zero value elements of the first row of the left multiplication matrix have completed the product operation, the first row of the output matrix is ​​obtained. 5. When all non-zero value elements of all rows of the left multiplication matrix (parallel calculations can be performed here) have completed the product operation, all rows of the output matrix are obtained. The left multiplication matrix and right multiplication matrix mentioned above refer to the query matrix and the key matrix respectively.

[0109] Step 5: Output each row of the rearranged output matrix to obtain the attention score matrix.

[0110] Since hash grouping may cause the order of the rows of the output matrix to be disrupted, it is necessary to rearrange them back to the original order. According to the original order index before hash grouping, the rows of the accumulated attention score matrix are rearranged to generate the final attention score matrix.

[0111] Specifically, hashing the dot product matrix includes: hashing the non-zero query vectors and key vectors in the dot product matrix multiple times; and assigning the query vectors and key vectors to different hash groups without duplication.

[0112] In practical applications, the entire process of hashing and grouping the dot product matrix includes the following steps: 1) Hash the non-zero Q and K vectors multiple times (randomly project them) and assign the vectors to unique hash groups. 2) For each query vector, only the key vector in the same hash group is used for attention score calculation, i.e. matrix multiplication. 3) After the grouping calculation is completed, the output is rearranged to form a unified attention map.

[0113] In one embodiment, a softmax calculation based on a shift operation is performed according to the attention score matrix, and the softmax calculation result includes:

[0114] Step 1: Divide the attention score matrix into several groups.

[0115] Divide the attention score matrix scores into several groups. This can be achieved by slicing on the sequence length (seq_length) or number of heads (num_heads) dimension.

[0116] Step 2: Find the maximum value in each group and obtain a preset second threshold, where the preset second threshold is determined based on the overall tensor corresponding to all the data in the group.

[0117] For each group of scores, find the maximum value x gmax i The search process can be processed in parallel. The preset second threshold T can be dynamically determined based on the statistical characteristics of the entire tensor, but it is more common to use a fixed ratio (such as a certain decimal multiple of the maximum value) as the threshold.

[0118] Step 3: Calculate the difference between each element in the group and the maximum value in the group. If the difference is greater than a preset second threshold, set the corresponding element to zero.

[0119] Each group calculates the difference x between the maximum value of the group and each element gmax i -x, if the result is greater than the threshold, that is, x gmax i -x>T, the element is set to zero (little impact on the result), and the calculation of subsequent steps is skipped.

[0120] Step 4: Calculate the difference power with 2 as the exponent base to get the intermediate result.

[0121] Calculation 2 (x-xgmax i) , and get an intermediate result. This intermediate result also needs to be passed through x max Compensate for the end result.

[0122] Step 5: Find the maximum value among all elements based on the maximum values ​​within different groups.

[0123] When all groups x gmax i After the search is complete, find the maximum value x among all elements max .

[0124] Step 6: Compensate the intermediate result with the maximum value of all elements, complete the softmax calculation through the shift operation, and get the softmax calculation result.

[0125] By x maxCompensate the intermediate results. Since 2 is the exponent base, only a simple shift operation is required here.

[0126] In one embodiment, dividing the attention score matrix into several groups includes:

[0127] The attention score matrix is ​​scaled by dividing it by the dimension of the key matrix to obtain a scaled attention score matrix; and the scaled attention score matrix is ​​divided into a number of groups.

[0128] Scale the attention score matrix S and divide it by Where dk is the dimension of the key), and then the scaled attention score matrix is ​​divided into several groups to reduce the amount of data processing. Here, the specific row-wise sparse matrix multiplication

[0129] It should be understood that, although the steps in the flowcharts involved in the above embodiments are displayed in sequence according to the indication of the arrows, these steps are not necessarily executed in sequence according to the order indicated by the arrows. Unless there is a clear explanation in this article, the execution of these steps is not strictly limited in order, and these steps can be executed in other orders. Moreover, at least a part of the steps in the flowcharts involved in the above embodiments may include multiple steps or multiple stages, and these steps or stages are not necessarily executed at the same time, but can be executed at different times, and the execution order of these steps or stages is not necessarily carried out in sequence, but can be executed in turn or alternately with other steps or at least a part of the steps or stages in other steps.

[0130] Based on the same inventive concept, the embodiment of the present application also provides an efficient sparse attention algorithm optimization device for implementing the efficient sparse attention algorithm optimization method involved above. The implementation scheme for solving the problem provided by the device is similar to the implementation scheme recorded in the above method, so the specific limitations in one or more embodiments of the efficient sparse attention algorithm optimization device provided below can refer to the limitations of the efficient sparse attention algorithm optimization method above, and will not be repeated here.

[0131] In one embodiment, Figure 4 As shown, an efficient sparse attention algorithm optimization device is provided, comprising:

[0132] A normalization module 200 is used to obtain the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data;

[0133] An attention processing module 400 is used to perform row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix;

[0134] A softmax calculation module 600, configured to perform a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result;

[0135] The attention calculation module 800 is used to perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

[0136] In one embodiment, the normalization module 200 is also used to obtain data to be processed; calculate the absolute value of each element in the data to be processed; retain the elements with a preset percentage before the absolute value and set the remaining elements to zero to obtain adjusted data; perform layernorm calculation on the adjusted data to obtain normalized data.

[0137] In one embodiment, the normalization module 200 is also used to identify non-zero elements in the adjusted data, calculate the square of the non-zero elements; if the square of the current non-zero element is less than a preset first threshold, the current non-zero element is set to zero; accumulate the element values ​​and square values ​​of the adjusted non-zero elements; and obtain the normalized layernorm output result of each element based on the element value and the square value.

[0138] In one embodiment, the attention processing module 400 is also used to apply a linear transformation to the normalized data to obtain a query vector, a key vector and a value vector; perform CSR compression on the query vector, the key vector and the value vector; calculate the dot product matrix of the query and the key based on the query vector and the key vector; perform hash grouping on the dot product matrix, perform row-wise sparse matrix multiplication on the query vector and the key vector in each hash group, and accumulate to obtain a row of the output matrix; output each row of the rearranged output matrix to obtain an attention score matrix.

[0139] In one of the embodiments, the attention processing module 400 is further used to hash the non-zero query vectors and key vectors in the dot product matrix multiple times; and to assign the query vectors and key vectors to different hash groups without duplication.

[0140] In one embodiment, the softmax calculation module 600 is also used to divide the attention score matrix into several groups; find the maximum value in each group and obtain a preset second threshold, which is determined based on the overall tensor corresponding to all the data in the group; calculate the difference between each element in the group and the maximum value in the group, and if the difference is greater than the preset second threshold, set the corresponding element to zero; calculate the power of the difference with 2 as the exponent base to obtain an intermediate result; based on the maximum values ​​in different groups, find the maximum value among all elements; compensate the intermediate result with the maximum value among all elements, complete the softmax calculation through a shift operation, and obtain the softmax calculation result.

[0141] In one embodiment, the softmax calculation module 600 is further used to scale the attention score matrix by dividing it by the dimension of the key matrix to obtain a scaled attention score matrix; and divide the scaled attention score matrix into a plurality of groups.

[0142] Each module in the above-mentioned efficient sparse attention algorithm optimization device can be implemented in whole or in part by software, hardware and their combination. The above-mentioned modules can be embedded in or independent of the processor in the computer device in the form of hardware, or can be stored in the memory of the computer device in the form of software, so that the processor can call and execute the operations corresponding to the above modules.

[0143] In one embodiment, a computer device is provided. The computer device may be a server, and its internal structure diagram may be as follows: Figure 5 As shown. The computer device includes a processor, a memory and a network interface connected through a system bus. Among them, the processor of the computer device is used to provide computing and control capabilities. The memory of the computer device includes a non-volatile storage medium and an internal memory. The non-volatile storage medium stores an operating system, a computer program and a database. The internal memory provides an environment for the operation of the operating system and the computer program in the non-volatile storage medium. The database of the computer device is used to store preset data. The network interface of the computer device is used to communicate with an external terminal through a network connection. When the computer program is executed by the processor, an efficient sparse attention algorithm optimization method is implemented.

[0144] Those skilled in the art will understand that Figure 5 The structure shown in the figure is only a block diagram of a part of the structure related to the solution of the present application, and does not constitute a limitation on the computer device to which the solution of the present application is applied. The specific computer device may include more or fewer components than those shown in the figure, or combine certain components, or have a different arrangement of components.

[0145] In one embodiment, a computer device is provided, including a memory and a processor, wherein a computer program is stored in the memory, and the processor implements the above-mentioned efficient sparse attention algorithm optimization method when executing the computer program.

[0146] In one embodiment, a computer-readable storage medium is provided, on which a computer program is stored, and when the computer program is executed by a processor, the above-mentioned efficient sparse attention algorithm optimization method is implemented.

[0147] In one embodiment, a computer program product is provided, including a computer program, which implements the above-mentioned efficient sparse attention algorithm optimization method when executed by a processor.

[0148] Those of ordinary skill in the art can understand that all or part of the processes in the above-mentioned embodiment methods can be completed by instructing the relevant hardware through a computer program, and the computer program can be stored in a non-volatile computer-readable storage medium. When the computer program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, any reference to the memory, database or other medium used in the embodiments provided in the present application can include at least one of non-volatile and volatile memory. Non-volatile memory can include read-only memory (ROM), magnetic tape, floppy disk, flash memory, optical memory, high-density embedded non-volatile memory, resistive random access memory (ReRAM), magnetoresistive random access memory (MRAM), ferroelectric random access memory (FRAM), phase change memory (PCM), graphene memory, etc. Volatile memory can include random access memory (RAM) or external cache memory, etc. As an illustration and not limitation, RAM can be in various forms, such as static random access memory (SRAM) or dynamic random access memory (DRAM). The database involved in each embodiment provided in this application may include at least one of a relational database and a non-relational database. Non-relational databases may include distributed databases based on blockchains, etc., but are not limited thereto. The processor involved in each embodiment provided in this application may be a general-purpose processor, a central processing unit, a graphics processor, a digital signal processor, a programmable logic device, a data processing logic device based on quantum computing, etc., but are not limited thereto.

[0149] The technical features of the above embodiments may be combined arbitrarily. To make the description concise, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.

[0150] The above-described embodiments only express several implementation methods of the present application, and the descriptions thereof are relatively specific and detailed, but they cannot be understood as limiting the scope of the present application. It should be pointed out that, for a person of ordinary skill in the art, several variations and improvements can be made without departing from the concept of the present application, and these all belong to the protection scope of the present application. Therefore, the protection scope of the present application shall be subject to the attached claims.

Claims

1. An efficient sparse attention algorithm optimization method, characterized in that: The method comprises: Acquire the data to be processed, and perform layernorm calculation based on importance perception on the data to be processed to obtain normalized data; Performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix; Performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result; Perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

2. The method according to claim 1, characterized in that The obtaining of the data to be processed and performing layernorm calculation based on importance perception on the data to be processed to obtain normalized data includes: Get the data to be processed; Calculating the absolute value of each element in the data to be processed; The elements with a preset percentage before the absolute value are retained, and the remaining elements are set to zero to obtain the adjusted data; Perform layernorm calculation on the adjusted data to obtain normalized data.

3. The method according to claim 2, characterized in that The performing layernorm calculation on the adjusted data to obtain normalized data includes: Identifying non-zero elements in the adjusted data, and calculating the square of the non-zero elements; If the square of the current non-zero element is less than the preset first threshold, the current non-zero element is set to zero; Accumulate the adjusted element values ​​and square values ​​of the non-zero elements; According to the element value and the square value, the layernorm output result of each element normalization is obtained.

4. The method according to claim 1, characterized in that: The normalized data is subjected to row-wise product sparse matrix multiplication and grouped hash multi-head attention processing to obtain an attention score matrix including: Applying a linear transformation to the normalized data to obtain a query vector, a key vector, and a value vector; Performing CSR compression on the query vector, key vector and value vector; Calculate a dot product matrix of query and key based on the query vector and the key vector; Hash grouping is performed on the dot product matrix, and row-wise sparse matrix multiplication is performed on the query vector and the key vector in each hash group, and the results are accumulated to obtain a row of the output matrix; Output rearranges each row of the output matrix to obtain an attention score matrix.

5. The method according to claim 4, characterized in that Hash grouping the dot product matrix includes: Hashing the non-zero query vectors and key vectors in the dot product matrix multiple times; The query vector and the key vector are assigned to different hash groups without duplication.

6. The method according to claim 1, characterized in that The softmax calculation based on the shift operation is performed according to the attention score matrix to obtain the softmax calculation result, including: Dividing the attention score matrix into a plurality of groups; Find the maximum value in each group and obtain a preset second threshold, where the preset second threshold is determined based on the overall tensor corresponding to all data in the group; Calculate the difference between each element in the group and the maximum value in the group, and if the difference is greater than the preset second threshold, set the corresponding element to zero; Calculate the difference value to a power with 2 as the exponent base to obtain an intermediate result; Find the maximum value among all elements based on the maximum values ​​in different groups; The intermediate result is compensated by the maximum value of all the elements, and the softmax calculation is completed by a shift operation to obtain a softmax calculation result.

7. The method according to claim 6, characterized in that The dividing the attention score matrix into several groups comprises: Scaling the attention score matrix by dividing it by the dimension of the key matrix to obtain a scaled attention score matrix; The scaled attention score matrix is ​​divided into several groups.

8. An efficient sparse attention algorithm optimization device, characterized in that: The device comprises: A normalization module, used for acquiring data to be processed, and performing layernorm calculation based on importance perception on the data to be processed to obtain normalized data; An attention processing module, used for performing row-wise sparse matrix multiplication and grouped hash multi-head attention processing on the normalized data to obtain an attention score matrix; A softmax calculation module, used for performing a softmax calculation based on a shift operation according to the attention score matrix to obtain a softmax calculation result; The attention calculation module is used to perform row-wise sparse matrix multiplication on the softmax calculation result and the median vector of the attention matrix to obtain the attention calculation result.

9. A computer device comprising a memory and a processor, wherein the memory stores a computer program, wherein: When the processor executes the computer program, the steps of the method according to any one of claims 1 to 7 are implemented.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that: When the computer program is executed by a processor, the steps of the method according to any one of claims 1 to 7 are implemented.

Citation Information

Patent Citations

  • Micro-expression recognition method and system based on sparse self-attention mechanism

    CN114743235A

  • Social hash for language models

    US10902221B1

  • Multi-scale transformer for image analysis

    WO2023277919A1

Cited By

  • Video generation acceleration method and device based on large model, equipment and medium

    CN121000954A

  • A large model-based video generation acceleration method, device, equipment and medium

    CN121000954B

  • Sparse attention calculation method and device for GPU and medium

    CN121683877A

  • A sparse attention calculation method, device and medium for a GPU

    CN121683877B

  • Method and apparatus for sparse attention mechanism

    WO2026178703A1