Multi-modal code searching method based on fine-grained attention alignment

Through the multi-modal code search method of fine-grained attention alignment, the multi-head attention mechanism and the joint attention mechanism are used to fuse the features of the code and the query, which solves the problems of insufficient information extraction and feature heterogeneity in code search, and achieves Enables efficient matching and accurate searching in large code databases.

CN118673091AActive Publication Date: 2024-09-20HOHAI UNIV
View PDF 3 Cites 0 Cited by

Patent Information

Application Number
CN202410630129.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-05-21
Publication Date
2024-09-20
Estimated Expiration
2044-05-21

AI Technical Summary

Technical Problem

Existing code search methods have problems such as incomplete information extraction and insufficient consideration of feature dimensions, which makes it difficult to align the heterogeneity between codes and queries, affecting the efficiency and accuracy of search results, especially in large-scale code databases. .

Method used

A multi-modal code search method based on fine-grained attention alignment is adopted. Through the multi-head attention mechanism and the joint attention mechanism, the text and structural features of the code and query are fused in different representations, using cross-entropy optimization and cosine similarity. Matching sorting solves the problem of feature heterogeneity and information redundancy.

Benefits of technology

It improves the matching effect of codes and queries, simplifies the search process in large code databases, enhances the accuracy and quality of search results, solves the problem of insufficient information feature extraction, and reduces errors caused by feature misalignment.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118673091A
    Figure CN118673091A
Patent Text Reader

Abstract

The invention discloses a multi-modal code search method based on fine-grained attention alignment, which learns rich semantics of source codes and natural language queries from two modals of text and structure by constructing a new mechanism, constructs a code search model by using a multi-modal feature network, adopts different construction modes for different modal features, and improves the search efficiency. Different features of corresponding codes and texts are fully expressed; meanwhile, a fine-grained alignment mechanism is adopted in the model training process, and same-modal features are aligned respectively, so that matching of code entities and text entities is facilitated; after construction of all features is completed, the similarity between a given query and code samples in all code libraries is calculated by using a cosine similarity function, so that similarity sorting is performed on the code samples. The method gets rid of insufficiency of code representation and feature extraction in the existing code search field, can more completely utilize information contained in different modal features to perform code representation and matching, and has higher recognition precision and better convergence performance.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The invention relates to a multimodal code search method based on fine-grained attention alignment, and belongs to the technical field of software engineering. Background Art

[0002] Software engineering refers to the discipline of planning, designing, building, testing and maintaining software by applying engineering principles, techniques and methods in the process of developing, maintaining and managing software systems. Software engineering aims to improve the efficiency, quality and reliability of software development to meet the needs of users. In modern society, software systems have been applied in various fields. There may be similar functions in different software systems, which means that their implementation codes are similar. With the rapid development of the software industry in the past few years, the number of source codes in the world has reached an unprecedented level. Obviously, the software industry has entered the era of big data, and code reuse is becoming more and more important. Code search, as a key task in the field of software engineering technology, aims to quickly and efficiently find code snippets that match the programming semantics and the intentions expressed by developers in natural language queries.

[0003] Current research shows that code search mainly uses information retrieval or deep learning. Existing research methods have problems such as incomplete information extraction and poor consideration of feature dimensions. Such information loss will have a great impact on the results of code search. The structure and syntax used by the code and the query itself are quite different, which means that the two cannot be directly or completely aligned; the rapid progress of science and technology has led to an exponential growth in the amount of code. In summary, the key challenges to achieving efficient code search are: the heterogeneity of queries and codes, the unified representation of embedded spaces, and the explosive growth of code databases. Summary of the invention

[0004] Purpose of the invention: In view of the problems and shortcomings in the prior art, the present invention provides a multimodal code search method based on fine-grained attention alignment, which can efficiently and quickly extract and fully align the multimodal information of the code in a large code database, so that the model can achieve a better search effect. The multimodal code search method based on fine-grained attention alignment proposed in the present invention can design different feature representation methods according to the different modal characteristics of the code itself, making the representation more accurate, thereby achieving a better matching effect between the query and the code.

[0005] Technical solution: A multimodal code search method based on fine-grained attention alignment. The present invention proposes that a fine-grained network adopts different feature representation methods for the text and structural features of the code and query, and at the same time, considering the feature differences, a fine-grained alignment mechanism is used to fuse the features of different modalities. The method comprises the following steps:

[0006] Step 1: Select code snippets from a code base consisting of code and comments. Preprocess the code and query to extract the corresponding text and structure representations.

[0007] Step 2: For the text features of code and query, a multi-head attention mechanism is used to represent them; for the structural features of code, some data streams are added on the basis of the abstract syntax tree to form a more detailed graph structure; for the structural features of query, a selection parse tree is used to represent it, and the NextToken edge is added to indicate its word order.

[0008] Step 3: Align the textual and structural feature representations of codes and queries respectively, and calculate the fine-grained correlation between different modal features to enhance the characteristics of codes and queries.

[0009] Step 4: Connect the different modal features obtained to obtain the final representation of the code and query, use cross entropy for optimization, and then match the code and query through step 5.

[0010] Step 5: Use the features optimized by cross entropy in step 4 as the final feature representation of the code and query, and sort all the code snippets according to their cosine similarity with the corresponding query. Based on the size of the cosine similarity, this method finally obtains a recommended code list corresponding to the query through sorting.

[0011] In the step 1, for the code snippets selected from the standardized code database, the text and structural information of the code are preprocessed and simply extracted. Generally speaking, the code text of all standardized code snippets can be divided into three parts: method name, API sequence and other tags. As can be seen from the naming specifications of the method name, the method name plays an important role in object-oriented programming and can accurately reflect the function and behavior of the method. In order to reduce the complexity of method processing, a new extraction method is innovatively used, that is, the code text only extracts the method name as a feature instead of using all the code text, and performs word segmentation operations on the extracted tokens containing specific symbols (such as _). The structural information of the code is mainly extracted by using tools to extract its corresponding abstract syntax tree.

[0012] In step 2, multi-head attention is used to represent the text information of the code and query. The multi-head attention mechanism is based on the self-attention mechanism and is widely used in natural language processing. The formula of the self-attention mechanism in Transformer can be expressed as:

[0013]

[0014] in, is the scaling factor used to correct the gradient, Q, K, and V represent query, key, and value.

[0015] The multi-head attention mechanism repeats the above self-attention mechanism process H times and then combines the outputs:

[0016] Mutihead(Q,K,V)=Concat(head 1 , ..., head H )W Model

[0017] where head i =Attention(QW i Q ,KW i K ,VW i V )

[0018] in, is the weight matrix of the attention mechanism, is the calculation parameter of the model, d Model It is W Model The corresponding matrix dimension is,H,the number of heads.,Through the multi-head attention mechanism, the relationships between,text words based on the same attention mechanism can be learned,and then combined as knowledge to capture short-term and long-term,dependencies at different ranges within the sequence.

[0019] A bidirectional gated graph neural network is used to construct a structural graph representation of code and queries. The structural graph is a heterogeneous graph, which is a graph composed of different types of entities and relationships, represented as nodes and edges respectively. Compared with traditional isomorphic graphs, heterogeneous graphs provide additional type information of nodes and edges. Such features can help represent different nodes and relationships contained in abstract syntax trees and selection parse trees. For each node in the structural graph, a SUM aggregation function is applied, which takes a set of incoming (or outgoing) adjacent node vectors as input and outputs a backward (or forward) aggregation vector, which is calculated as follows:

[0020]

[0021]

[0022] in, represents the eigenvector of the u-th neighboring point, and Represents all adjacent points in the forward and backward directions.

[0023] Fusion of node embeddings from forward and backward:

[0024]

[0025] This Fuse function calculates the gated sum of the two inputs and finally provides the result to the Gated Recurrent Unit (GRU) to update the node representation:

[0026]

[0027] After K-hop calculation, the final node representation is obtained Then we apply max pooling on all nodes to get the final graph representation:

[0028]

[0029] Among them, MaxPool represents the maximum pooling layer, and FC represents the fully connected layer.

[0030] In step 3, the two modal features of the code and query obtained in step 2 are used for fine-grained alignment. The main step is to align the structural features and text features separately, so as to completely solve the errors caused by feature heterogeneity in matching. The input sequence is weighted using a joint attention mechanism so that the model can focus on different levels of information. The key idea of ​​this mechanism is to explore finer-grained semantic correlations between the same modal features of each code and query in order to enrich their representations separately.

[0031] As far as text features are concerned, the calculation process is as follows:

[0032] Attention=Code token T ·Query token

[0033] in and Represent the text embedding representation of code and query respectively, m and n represent the dimensions of the matrix. After the above calculation, the rows and columns of the Attention matrix represent the relevant information of the code and query respectively.

[0034] Use the SoftMax function to normalize the rows and columns separately:

[0035] α Code =SoftMax(Attention)

[0036] α Query =SoftMax(Attention T )

[0037] The α obtained after normalization Code and α Query are the weight coefficients corresponding to the code and the query respectively, and the obtained weight coefficients are used to perform dot product calculation to obtain the new final text feature representation:

[0038] New_Query token =α Query ·Query token

[0039] New_Code token =α Code Code token

[0040] In terms of structural features, the calculation process is as follows:

[0041] Attention=Code structure T ·Query structure

[0042] in and Represent the structural embedding representation of code and query respectively, m and n represent the dimensions of the matrix. After the above calculation, the rows and columns of the Attention matrix represent the relevant information of the code and query respectively.

[0043] Use the SoftMax function to normalize the rows and columns separately:

[0044] α Code =SoftMax(Attention)

[0045] α Query =SoftMax(Attention T )

[0046] The α obtained after normalization Code and α Query are the weight coefficients corresponding to the code and the query respectively, and the obtained weight coefficients are used to perform dot product calculation to obtain the new final structural feature representation:

[0047] New_Query structure =α Query ·Query structure

[0048] New_Code structure =α Code Code structure

[0049] In step 4, the text features and structural features of the query are combined to generate a joint feature representation Query fusion , the text features and structural features of the code are combined to generate a joint feature representation Code fusion , and use cross entropy as the loss function to optimize the joint feature representation:

[0050]

[0051] Among them, c i represents the target code feature representation, c j represents other interference code features and i≠j, q i represents the target query feature representation, and the base of log is e. The main purpose of the loss function is to minimize q i Its corresponding code c i The inner product between them, while maximizing q i and other interference codes c j The inner product between .

[0052] The main purpose of the loss function is to minimize q i Its corresponding code c i The inner product between them, while maximizing q i and other interference codes c j The inner product between .

[0053] Step 5 matches and sorts all code snippets based on the final joint feature representation of the code and query obtained in step 4 after cross entropy optimization. Cosine similarity is used as the matching index, and its calculation formula is as follows:

[0054]

[0055] The higher the cosine similarity score, the more the code snippet matches the corresponding query and the higher it ranks in the returned list.

[0056] Beneficial effects: Compared with the prior art, the multimodal code search method based on fine-grained attention alignment provided by the present invention has the following advantages:

[0057] (1) The proposed fine-grained co-attention multimodal representation learning framework for code search uses only method names in text feature extraction of codes for the first time and proves to be non-destructive to search results, which helps to simplify matching in large code databases.

[0058] (2) The selection parse tree is used in the structural representation of natural language text, which is more similar to the abstract syntax tree corresponding to the code structure, thus promoting fine-grained alignment.

[0059] (3) The fine-grained alignment mechanism adopted can more deeply compare the features of different modalities of code and query, and solve the problem of information overlap or redundancy caused by the heterogeneity of code and query.

[0060] (4) The present invention solves the problem of insufficient information feature extraction in the field of code search, gets rid of the feature misalignment caused by the essential differences in structure and text, can select appropriate features in a large code database for query matching and improve search quality, and effectively solves some pain points in the field of code search. BRIEF DESCRIPTION OF THE DRAWINGS

[0061] Figure 1 is a flow chart of a method according to an embodiment of the present invention;

[0062] Figure 2 A schematic diagram of a preprocessing code in an example implementation of the present invention;

[0063] Figure 3 A schematic diagram of preprocessing a query in an example implementation of the present invention;

[0064] Figure 4 The figure is a schematic diagram of a fine-grained alignment mechanism in an example implementation of the present invention. DETAILED DESCRIPTION

[0065] The present invention is further explained below in conjunction with specific embodiments. It should be understood that these embodiments are only used to illustrate the present invention and are not used to limit the scope of the present invention. After reading the present invention, various equivalent forms of modifications to the present invention by those skilled in the art all fall within the scope defined by the claims attached to this application.

[0066] like Figure 1 As shown in FIG. 1 , the multimodal code search method based on fine-grained attention alignment includes the following steps:

[0067] Step 1: Use the canonical code database containing <code, comment> pairs as the code search dataset, where the comments are regarded as their corresponding queries, and divide the code search dataset into training set, test set and validation set according to the set ratio of 8:1:1. For each canonical code snippet in the code dataset, it contains two parts: code and query. Figure 1 The leftmost part shown in the figure is a standard code snippet, the thin part is the corresponding code itself, and the bold part "Extracts video IDfrom URL." is the comment corresponding to the code, that is, the query.

[0068] Preprocess the code and query separately. For the code, Figure 2 As shown in the figure, the sequence of method names for the extracted text part is ['def', 'get', 'vid', 'from', 'url', '(', 'url', ')'], and the tool is used to build the abstract syntax tree corresponding to the code; as for the query, Figure 3As shown, the sequence of the extracted text part is ['Extracts', 'video', 'ID', 'from', 'URL'], and the tool is used to build the selection parse tree corresponding to the natural language text.

[0069] Step 2: Use different feature representation methods for different modal features of code and query. For text, use a multi-head attention mechanism, and set the word embedding dimension size to 128. The specific formula is:

[0070] Mutihead(Q,K,V)=Concat(head 1 , ..., head H )W Model

[0071] where head i =Attention(QW i Q , KW i K , VW i V )

[0072] Corresponding to the structure, NextToken, ReturnTo, and SubToken edges are added to the abstract syntax tree corresponding to the code, and NextToken edges are added to the selection parsing tree corresponding to the query. After enriching the structural information, a bidirectional gated graph neural network is used to encode the structure. The dimension size of the hidden layer in the graph neural network is set to 128. The specific formula is:

[0073]

[0074]

[0075] Step 3 and Step 4: For the text and structure feature representations of codes and queries, the fine-grained correlation between different modal features is calculated to enhance the characteristics of codes and queries. Taking text features as an example, the structure of the fine-grained alignment mechanism is as follows: Figure 4 shown.

[0076] First, perform a dot product calculation on the obtained code and the text representation corresponding to the query:

[0077] Attention=Code token T ·Query token

[0078] in and Represent the text embedding representation of code and query respectively, m and n represent the dimensions of the matrix. After the above calculation, the rows and columns of the Attention matrix represent the relevant information of the code and query respectively.

[0079] Use the SoftMax function to normalize the rows and columns separately:

[0080] α Code =SoftMax(Attention)

[0081] α Query =SoftMax(Attention T )

[0082] The α obtained after normalization Code and α Query are the weight coefficients corresponding to the code and the query respectively, and the obtained weight coefficients are used to perform dot product calculation to obtain the new final text feature representation:

[0083] New_Query token =α Query ·Query token

[0084] New_Code token =α Code Code token

[0085] Similarly, the final structural feature representation New_Query can be obtained structure and New_Code structure The query text features and structural features are combined to form a joint feature representation Query fusion , the text features and structural features of the code are combined to generate a joint feature representation Code fusion , and use cross entropy as the loss function to optimize it:

[0086]

[0087] Step 5: Match and sort all code snippets based on the code obtained in step 4 and the final representation of the query. Cosine similarity is used as the matching index, and its calculation formula is as follows:

[0088]

[0089] A score sort is performed by cosine similarity, and finally a csv file containing the query, code and cosine similarity score is output as the final code search result.

[0090] The present invention is trained on a normalized large-scale code database, and uses the proposed multimodal code search method based on fine-grained attention alignment. First, the text and structural features of the code and query are preprocessed, and the information contained therein is fully extracted using different representation methods to avoid information redundancy and missing; secondly, the features of the two modes are aligned separately using a fine-grained alignment mechanism to retain the available information corresponding to each mode; finally, the cosine similarity score is used for sorting, and the corresponding result list is returned. The present invention solves the problem that the existing research methods are not sufficient for extracting and processing the required feature information for matching, avoids the information bias problem caused by the direct fusion of different feature modes, and can appropriately extract the required features for query and code matching in a code base with a large cardinality, and has a high accuracy rate.

[0091] The above are only preferred embodiments of the present invention. It should be pointed out that for ordinary technicians in this technical field, several improvements and modifications can be made without departing from the principles of the present invention. These improvements and modifications should also be regarded as the scope of protection of the present invention.

Claims

1. A multimodal code search method based on fine-grained attention alignment, It is characterized in that The method comprises the following steps: Step 1: Select code snippets from a code base consisting of code and comments; preprocess the code and query to extract the corresponding text and structure representation; Step 2: For the text features of the code and query, a multi-head attention mechanism is used to represent them; For the structural features of the code, some data streams are added on the basis of the abstract syntax tree to form a graph structure; for the structural features of the query, the selection parse tree is used to represent it, and the NextToken edge is added to represent its word order; Step 3: Align the text and structure feature representations of the code and query respectively, and calculate the fine-grained correlation between the features of different modalities; Step 4: Connect the obtained different modal features to obtain the final representation of the code and query, and use cross entropy for optimization; Step 5: Use the features optimized by cross entropy in step 4 as the final feature representation of the code and query, and sort all the code snippets according to their cosine similarity with the corresponding query; based on the size of the cosine similarity, this method finally obtains a recommended code list corresponding to the query through sorting.

2. The multimodal code search method based on fine-grained attention alignment according to claim 1, It is characterized in that In the step 1, for the code snippet selected from the code database, the code text of the code snippet is divided into three parts: method name, API sequence and other tags. Only the method name is extracted as a feature, and a word segmentation operation is performed on the extracted tokens containing specific symbols; for the structural information of the code, the corresponding abstract syntax tree is extracted.

3. The multimodal code search method based on fine-grained attention alignment according to claim 1, It is characterized in that In step 2, multi-head attention is used to represent the text information of the code and the query; the self-attention mechanism formula in Transformer is expressed as: in, is the scaling factor used to correct the gradient, Q, K, and V represent query, key, and value; The multi-head attention mechanism repeats the above self-attention mechanism process H times and then combines the outputs: Mutihead(Q,K,V)=Concat(head 1 ,...,head H )W Model where head i =Attention(QW i Q ,KW i K ,VW i V ) in, is the weight matrix of the attention mechanism, is the calculation parameter of the model, d Model It is W Model The corresponding matrix dimension, H is the number of heads; through the multi-head attention mechanism, the relationship between text words based on the same attention mechanism is learned, and then they are combined as knowledge to capture short-term and long-term dependencies in different ranges within the sequence; A bidirectional gated graph neural network is used to construct a structural graph representation of code and query; the structural graph is a heterogeneous graph, which is a graph composed of different types of entities and relationships, represented as nodes and edges respectively; for each node in the structural graph, a SUM aggregation function is applied, which takes a set of incoming or outgoing adjacent node vectors as input and outputs a backward and forward aggregation vector, which is calculated as follows: in, represents the eigenvector of the u-th neighboring point, and Represents all adjacent points in the forward and backward directions; Fusion of node embeddings from forward and backward: This Fuse function calculates the gated sum of the two inputs and finally provides the result to the gated recurrent unit to update the node representation: After K-hop calculation, the final node representation is obtained Then we apply max pooling on all nodes to get the final graph representation: Wherein MaxPo01 represents the maximum pooling layer, and FC represents the fully connected layer; according to the multimodal code search method based on fine-grained attention alignment according to claim 1, it is characterized in that, in the step 3, the two modal features of the code and the query obtained in step 2 are used for fine-grained alignment processing; the main step is to align the structural features and the text features respectively, so as to completely solve the errors caused by the feature heterogeneity in the matching; the input sequence is weighted using the common attention mechanism so that the model can pay attention to information of different degrees; the key idea of ​​this mechanism is to explore the finer-grained semantic correlation between the same modal features of each code and query in order to enrich their representations respectively.

4. The multimodal code search method based on fine-grained attention alignment according to claim 3, It is characterized in that As far as text features are concerned, the calculation process is as follows: Attention=Code token T ·Query token in and Represent the text embedding representation of code and query respectively, m and n represent the dimensions of the matrix; after the above calculation, the rows and columns of the Attention matrix represent the relevant information of the code and query respectively; Use the SoftMax function to normalize the rows and columns separately: a Code =SoftMax(Attention) a Query =SoftMax(Attention T ) The α obtained after normalization Code and α Query are the weight coefficients corresponding to the code and the query respectively, and the obtained weight coefficients are used to perform dot product calculation to obtain the new final text feature representation: New_Query token =α Query ·Query token New_Code token =α Code ·Code token 。 5. The multimodal code search method based on fine-grained attention alignment according to claim 3, It is characterized in that In terms of structural features, the calculation process is as follows: Attention=Code structure T ·Query structure in and They represent the structural embedding representation of code and query respectively, and m and n represent the dimensions of the matrix. After the above calculation, the rows and columns of the Attention matrix represent the relevant information of the code and query respectively. Use the SoftMax function to normalize the rows and columns separately: a Code =SoftMax(Attention) a Query =SoftMax(Attention T ) The α obtained after normalization Code and α Query are the weight coefficients corresponding to the code and the query respectively, and the obtained weight coefficients are used to perform dot product calculation to obtain the new final structural feature representation: New_Query structure =α Query ·Query structure New_Code structure =α code ·Code structure 。 6. The multimodal code search method based on fine-grained attention alignment according to claim 1, It is characterized in that In step 4, the text features and structural features of the query are combined to generate a joint feature representation Query fusion , the text features and structural features of the code are combined to generate a joint feature representation Code fusion , and use cross entropy as the loss function to optimize the joint feature representation: Among them, c i represents the target code feature representation, c j represents other interference code features and i≠j, q i represents the target query feature representation, the base of log is e; The main purpose of the loss function is to minimize q i Its corresponding code c i The inner product between them, while maximizing q i and other interference codes c j The inner product between .

7. The multimodal code search method based on fine-grained attention alignment according to claim 1, It is characterized in that Step 5 matches and sorts all code snippets based on the final joint feature representation of the cross-entropy optimized code and the query obtained in step 4; cosine similarity is used as the matching index, and its calculation formula is as follows: The higher the cosine similarity score, the more the code snippet matches the corresponding query and the higher it ranks in the returned list.

Citation Information

Patent Citations

  • Code searching method based on two-stage attention mechanism

    CN112800172A

  • Semantic code searching method based on fine-grained common attention mechanism

    CN114237621A

  • Code search method based on multi-modal representation

    CN117390130A