Code annotation generation method based on grammar optimization and context enhancement
By constructing a multimodal model and combining syntax optimization and context enhancement methods, the shortcomings of existing code annotation generation technologies in long sequence processing are addressed, achieving higher quality and more comprehensive code annotation generation.
Patent Information
- Application Number
- CN202410973813.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-19
- Publication Date
- 2024-11-15
- Estimated Expiration
- Not applicable · inactive patent
AI Technical Summary
Existing code annotation generation techniques perform poorly when dealing with long sequences of remote dependencies. Tree-based models may fail to fully capture the hierarchy and semantic relationships of the code due to flattening or loss of structural information, while graph-based models are complex to build and process and lack sufficient semantic information.
We employ a syntax optimization and context enhancement approach. By constructing function code-reference annotation pairs, we segment the dataset and generate Code-Token, Context-PDG, and VFO-AST modalities. We use a joint decoder combining GRU and GAT encoders with an attention mechanism to generate code annotations, simplifying the AST structure and enriching the PDG node information.
It improves the quality and comprehensiveness of code comments, enhances the model's understanding and accuracy of code semantics and dependencies, simplifies the complexity of the AST, and strengthens the semantic information expression of PDG nodes.
Smart Images

Figure CN118963824A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of code comment generation, and in particular to a method for generating code comments based on grammar optimization and context enhancement. Background Art
[0002] The complexity of software code structure and the variability of software projects have made code comments increasingly important. High-quality code comments support high maintainability and high availability of software. Research shows that developers need to spend an average of 59% of their time on program understanding, which proves the importance of software code comments to program understanding. However, manually writing code comments takes a lot of time, which is not only inefficient, but also has uneven quality, and the correctness of manually written comments is difficult to guarantee. This shows the importance of automatic code comment generation technology. Automatic code comment generation technology is a cross-application of computer science and natural language processing (NLP). It combines code analysis, natural language understanding, and text generation technology to improve the readability, comprehensibility, and maintainability of code.
[0003] The emergence of deep learning technology has greatly promoted the development of program understanding, making the research on code summarization mainly focus on the encoder-decoder structure. At present, the code representation problem has become the focus of research. The traditional method of representing code as a sequence does not work well when processing long sequences. Although the abstract syntax tree (AST) can retain structural information, due to the large and deep structure of the AST, directly inputting the model will consume a lot of resources and may cause gradient vanishing or explosion problems. In addition, converting the AST into a sequence will lose structural semantics. Therefore, how to effectively extract structural semantic information in the AST has become a research focus. Although some studies have tried to solve these problems by cutting the AST, this method has not fundamentally solved the problem of redundant information in the AST. Since then, researchers have proposed using control flow graphs (CFGs), data flow graphs (DFGs), and program dependency graphs (PDGs) to represent code. These graphs can capture the control flow and data flow dependencies in the code, but usually only focus on the statement level, ignoring the contextual semantics, which limits the model's ability to extract the semantics and structural information of the code. Therefore, how to combine multiple code representation methods to enrich the semantic information of the code has also become an important research direction.
[0004] Existing code comment generation technologies are basically based on code representation. Code representation is a very important part of the code annotation task. Good code representation can better reflect the syntax, semantics and timing information of the code. Existing code representation methods mainly include sequence representation, AST representation and graph representation.
[0005] A simple approach is to directly convert the code into a sequence of natural language descriptions. This approach almost always regards the code comment generation task as a sequence-to-sequence (Seq2Seq) task and encodes and decodes the sequence using models such as RNN. Allamanis et al. [1] and Iyer et al. [2] regard the source code as plain text and use traditional token-based methods to capture vocabulary information. Gu et al. [3] use the Seq2Seq model to learn the intermediate vector representation of natural language queries. Later, in order to solve the long-range dependency problem of long sequences, research work turned to using advanced methods such as transformers [4] to process long sequences.
[0006] Code annotation models based on sequence representation, such as the Seq2Seq model, are easy to operate, but perform poorly when dealing with long-range dependencies in long sequences, which may result in the generated annotations failing to meet the needs of complex code. Although models based on tree representation provide richer grammatical structure information, they may fail to fully capture the hierarchy and semantic relationships of the code in some cases due to flattening or loss of structural information. On the other hand, although models based on graph representation (such as DFG, CFG, and PDG) can fully describe the dependencies and process characteristics of a program, they are complex to construct and process, and the fine-grained information of graph nodes may lead to a lack of sufficient semantic information, requiring more complex models and algorithms to effectively capture and utilize the information in the graph. Therefore, a method for generating code annotations based on grammar optimization and context enhancement is invented. Summary of the invention
[0007] In view of the above problems and / or the problems existing in an existing method for generating code comments based on syntax optimization and context enhancement, the present invention is proposed.
[0008] Therefore, the purpose of the present invention is to provide a method for generating code comments based on syntax optimization and context enhancement, which can solve the above-mentioned existing problems.
[0009] To solve the above technical problems, according to one aspect of the present invention, the present invention provides the following technical solutions:
[0010] A method for generating code comments based on syntax optimization and context enhancement includes the following specific steps:
[0011] S100, constructing function code / reference annotation pairs: constructing function codes in the data set and their corresponding reference annotations into function code / reference annotation pairs, and then all function code-reference annotation pairs constitute a function code-reference annotation pair data set;
[0012] S200, split the data set: After shuffling the data set, split it into a training set, a validation set, and a test set, ensuring that the three subsets are independent of each other and do not overlap;
[0013] S300, function code preprocessing: including normalizing the code, generating PDG and AST, and then using corresponding methods to generate Code-Token mode, Context-PDG mode and VFO-AST mode;
[0014] S400, constructing a code annotation vocabulary: constructing a code annotation vocabulary using reference annotations in function code-reference annotation pairs in a training set;
[0015] S500, constructing a multimodal model: constructing a GRU-based encoder GRU_Encoder, a GAT-based encoder GATEncoder_AST, a GAT-based encoder GATEncoder_PDG, and constructing a joint decoder Joint-Decoder;
[0016] S600, model training: the training set and validation set are used for model training, and the test set is used to evaluate model performance;
[0017] S700, generating target code function annotations: when receiving target code function data, performing function code preprocessing operations on it, and using a multimodal network model to generate corresponding target code function annotations.
[0018] As a preferred solution of the method for generating code annotations based on grammar optimization and context enhancement described in the present invention, the Code-Token modal generation process in S300 is as follows: the camel case words in the function code are cut according to the camel case naming rule, and then the snake case words in the function code are cut according to the snake case naming rule, and then the code is normalized, and the normalization operation includes: adding spaces between words, between words and punctuation marks, and between punctuation marks in the function code to ensure that words and punctuation marks are regarded as independent entities, and then, using the code after the above processing to build a code vocabulary, the code vocabulary consists of "index key-code value", and then the code vocabulary is stored in the code_vocab.pk file, and then a code tag embedding layer is built, and the preprocessed code is mapped through the code vocabulary to obtain a code vector v code-token , then the vector v code-token After the code vocabulary embedding layer, the Code-Token modality is obtained, denoted as Modal Code-Token .
[0019] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the VFO-AST modal generation process in S300 is as follows: an abstract syntax tree generation tool is used to generate the corresponding AST from the function code, and the information carried in each node in the obtained AST includes: node type type, node value value, and node subtree set children.
[0020] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the Context-PDG modal generation process in S300 is as follows: a program dependency graph generation tool is used to generate the corresponding PDG from the function code, recorded as the original PDG, and the information carried by each node in the obtained original PDG includes: node type type, node value value, and the node's subtree set children. The information carried by each edge in the PDG includes: edge attribute type, the starting node of the edge, and the ending node of the edge.
[0021] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the specific process of S400 is as follows:
[0022] S410: Process the reference annotation, that is, perform camel case cutting, snake case cutting, and normalization operations on the value of the node;
[0023] S420: Then, a code comment vocabulary is constructed using the processed reference comments. The code comment vocabulary is composed of "index key-code value", and then the code comment vocabulary is stored in the comment_vocab.pk file.
[0024] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the specific process of constructing the GRU-based encoder GRU_Encoder in S500 is as follows: The encoder GRU_Encoder is used to receive Modal Code-Token , use bidirectional GRU to Modal Code-Token Encode and generate hidden codeToken as well as After that, the output and embedding vector of GRU are further processed through a fully connected layer, and the encoded representation is finally generated as hi idden codeToken , the process is expressed using the following formula:
[0025]
[0026] in, represents the output encoding representation at time step i, hidden codeToken is the hidden state after BiGRU encoding, Represents the input embedding vector of the i-th step, in fact Modal Code-Token That is The output obtained in the last time step is recorded as Output codeToken .
[0027] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the specific process of constructing the GAT-based encoder GATEncoder_AST and the encoder GATEncoder_PDG in S500 is as follows: the encoder GATEncoder_AST and the encoder GATEncoder_PDG are respectively used to receive Modal VFO-AST Modal Context-PDG , where Modal VFO-AST The steps in the encoder GATEncoder_AST are: Modal VFO-AST After passing through the GAT layer, get Out GAT_AST , and then further processed by a BiGRU layer to capture the contextual information in the graph, and finally get Output GAT_AST ,hidden GAT_AST Similarly, Modal Context-PDG Get Output through encoder GATEncoder_PDG GAT_PDG ,hidden GAT_PDG .
[0028] As a preferred solution of the method for generating code annotations based on syntax optimization and context enhancement described in the present invention, the specific process of constructing the joint decoder Joint-Decoder in S500 is as follows:
[0029] Process 1: Joint-Decoder receives Output codeToken 、hidden codeToken 、Output GAT_AST 、hidden GAT_AST 、Output GAT_PDG and hidden GAT_PDG , use the attention mechanism to calculate the Output separately codeToken 、Output GAT_AST and Output GAT_PDG The attention weights are obtained. AttnCT 、Out AttnVAST and OutAttnCPDG ;
[0030] The calculation formula of its attention score is:
[0031]
[0032] Among them, h t is the hidden state of the decoder at time t. When t = 0, hidden codeToken ,s i is the ith hidden state of Output, W a and v a is a learnable parameter, Indicates v a The transpose of
[0033] The calculation formula of its attention weight is:
[0034]
[0035] Among them, T is the length of the sequence corresponding to Output, α ti represents the attention weight of the decoder on the i-th hidden state of Output at time step t, and exp() is an exponential function;
[0036] Process 2: Out AttnCT and Out AttnVAST Perform weighted addition and then add it to Out AttnCPDG Perform vector concatenation to get Out JointVector ;
[0037] The steps for obtaining the weight of weighted addition are as follows: first, codeToken and hidden GAT_AST After splicing, we get h t , and then h t The weight coefficient gridWeight is obtained through the softmax layer, linear layer and sigmoid layer respectively. The calculation formula of the weight coefficient gridWeight is:
[0038] gridWeigh t=Sigmoid(Linear(softmax(h t )));
[0039] Process 3: Out JointVector After passing into the GRU-based decoder, it passes through a Linear layer to obtain the vocabulary distribution vector V wordDis , use greedy decoding to convert V wordDis A series of code comment indexes are obtained by step-by-step decoding, and the code comments are obtained by mapping the indexes to the code comment vocabulary.
[0040] As a preferred solution of the method for generating code comments based on syntax optimization and context enhancement described in the present invention, the specific process of S600 is as follows: Code-Token Modal VFO-AST Modal Context-PDG Training the network model architecture includes: Code-Token Modal VFO-AST Modal Context-PDG Input the initial function annotation generation model, generate the corresponding training function code annotation, and then calculate the loss value between the function code annotation generated by the training function code and the associated reference annotation. The training goal is to make the generated annotation most similar to the reference annotation. Select CrossEntropyLoss as the loss function. The formula of the loss function Loss is:
[0041]
[0042] Where p is the predicted annotation, y is the reference annotation, T is the length of the reference annotation sequence, and y t is the reference vocabulary at time step t, is the model's prediction of the reference vocabulary y at time step t t The predicted probability of
[0043] Then set a threshold for the training loss value. First, determine the number of consecutive loss calculation rounds m and the standard threshold threshold. The parameters are determined by the model trainer based on actual conditions. Calculate the average loss value of m rounds in succession, and compare the difference between the average loss value of the current round and the loss value of the previous round. If the absolute values of all these differences are less than the threshold, stop training and generate a multimodal network model; otherwise, automatically adjust the parameters of the encoder and decoder according to the preset gradient.
[0044] Compared with existing technologies:
[0045] The present invention represents the code as an abstract syntax tree and a program dependency graph, and proposes two algorithms to simplify the structure of AST and expand the information of PDG nodes. Through these transformations, two new modalities are generated: VFO-AST and Context-PDG. These improvements aim to reduce the complexity of AST, enrich the semantic information of PDG nodes, and fuse different code representation forms through a multimodal approach to obtain richer code representation, thereby generating higher quality code comments. BRIEF DESCRIPTION OF THE DRAWINGS
[0046] Figure 1 It is a flow chart of the present invention;
[0047] Figure 2 This is a model architecture diagram of the present invention;
[0048] Figure 3 The AST of the present invention is converted into a VFO-AST diagram;
[0049] Figure 4 The PDG of the present invention is converted into a Context-PDG graph. DETAILED DESCRIPTION
[0050] In order to make the objectives, technical solutions and advantages of the present invention more clear, the embodiments of the present invention will be further described in detail below with reference to the accompanying drawings.
[0051] The present invention provides a method for generating code comments based on syntax optimization and context enhancement, see Figure 1-Figure 4 , including the following specific steps:
[0052] S100, constructing function code / reference annotation pairs: constructing function codes in the data set and their corresponding reference annotations into function code / reference annotation pairs, and then all function code-reference annotation pairs constitute a function code-reference annotation pair data set;
[0053] S200, split the data set: After shuffling the data set, split it into a training set, a validation set, and a test set, ensuring that the three subsets are independent and non-overlapping; generally, the number of samples in the training set is significantly larger than that in the validation set and the test set, while the number of samples in the validation set and the test set is usually the same; in this method, it is recommended to use 80% of the data set for training, 10% for validation, and 10% for testing; in addition, shuffling refers to randomly arranging the samples in the data set, which is intended to prevent the model from learning the order of the data samples during training, thereby introducing bias and errors;
[0054] S300, function code preprocessing: including normalizing the code, generating PDG and AST, and then using corresponding methods to generate Code-Token mode, Context-PDG mode and VFO-AST mode; the three modes are processed in parallel, that is, their preprocessing processes do not interfere with each other;
[0055] in:
[0056] The Code-Token modal generation process in S300 is as follows: the camel case words in the function code are cut according to the camel case naming rule, and then the snake case words in the function code are cut according to the snake case naming rule, and then the code is normalized. The normalization operation includes: adding spaces between words, between words and punctuation marks, and between punctuation marks in the function code to ensure that words and punctuation marks are regarded as independent entities, and deleting escape characters such as "\r", "\n" and "\t"; converting all function codes to lowercase, and then using the above-processed code to build a code vocabulary, the code vocabulary consists of "index key-code value", and then the code vocabulary is stored in the code_vocab.pk file (the index key is numbered from 0 and increments in sequence. For example, the code value corresponding to the index key 1 is "code", and the storage format in the code vocabulary is: {key:1, value:"code"}), and then a code token embedding layer is constructed to map the preprocessed code through the code vocabulary to obtain the code vector v code-token , then the vector v code-token After the code vocabulary embedding layer, the Code-Token modality is obtained, denoted as Modal Code-Token (In pytorch, the embedding layer is constructed by torch.nn.Embedding); CamelCase: The camelCase naming rule is to connect multiple words together and capitalize the first letter of each word to form a single identifier, such as "my Function Name" is "myFunctionName" after camelCase naming; SnakeCase: The snakeCase naming rule is to connect multiple words together and use underscores _ to separate each word to form a single identifier; for example, "my variable name" is "my_variable_name" after snakeCase naming;
[0057] The VFO-AST modal generation process in S300 is as follows: Use the abstract syntax tree generation tool to generate the corresponding AST from the function code. The information carried in each node in the obtained AST includes: node type type, node value value, and node subtree set children;
[0058] The present invention proposes a value-free optimization AST algorithm (Value-Free Optimization, VFO), and the specific algorithm steps are:
[0059] First, traverse and filter nodes, use the depth-first algorithm to traverse the AST, assume that the currently traversed node is cur, take out all child nodes of cur from the subtree set children of cur, and determine whether each child node of cur has a value item in turn:
[0060] If the node has a value item, it is retained;
[0061] If the node does not have a value item, determine whether its type item is body:
[0062] If the node type is body, keep it;
[0063] The purpose of retaining nodes with type body is to avoid a single node carrying too many child nodes, and this can maintain the grammatical structure of AST to a certain extent;
[0064] If the node type is not body, record this node as Node Ready2Delete , delete the Node in the children collection in cur Ready2Delete , then use the depth-first algorithm to traverse the Node Ready2Delete All child nodes of , add all node numbers with value items or type body to the children list in cur;
[0065] Thus, we get the valueless optimized AST, denoted as VFO-AST; Figure 3 An example of the conversion diagram from the original AST to the VFO-AST;
[0066] Furthermore, all nodes in VFO-AST are traversed and the value of the node is processed, that is, the value of the node is cut into camel case, cut into snake case, and normalized; the value in the AST node is actually a code;
[0067] Next, use the value of the AST node to build the AST node vocabulary, which is composed of "index key-code value", and then store the AST node vocabulary in the ast_vocab.pk file;
[0068] Construct an AST graph embedding layer, which consists of a node embedding layer and an edge embedding layer; map all nodes in the AST through the AST node vocabulary to obtain the AST node vector v AST , then the vector v AST Through the AST node embedding layer, we get the node embedding vector v AST_nodeEmbed ; Use the depth-first algorithm to traverse the AST and store the edge relationships between nodes in the adjacency matrix. Next, add each node to its own edge, that is, set all the diagonals of the adjacency matrix to 1, then convert the adjacency matrix to a symmetric matrix, and finally pass the adjacency matrix through the edge embedding layer to get v AST_matrix; The VFO-AST after the graph embedding layer is called VFO-AST modality, denoted as Modal VFO-AST ; In pytorch, the node embedding layer is constructed by torch.nn.Embedding; the edge embedding layer actually converts the adjacency matrix into a tensor, and the code is: torch.Tensor(adjacent), where adjacent is the adjacency matrix;
[0069] The Context-PDG modality generation process in S300 is as follows: Use the program dependency graph generation tool to generate the corresponding PDG from the function code, which is recorded as the original PDG. The information carried by each node in the obtained original PDG includes: node type type, node value value, and node subtree set children. The information carried by each edge in the PDG includes: edge attribute type (type is generally control flow or data flow), edge start node, and edge end node;
[0070] The present invention proposes a contextual PDG information enhancement algorithm (Contextual PDG Enhancer, CPE), and the specific algorithm steps are:
[0071] The first step is to traverse the PDG and store all nodes in a dictionary node_dict;
[0072] The second step is to create a control flow list and a data flow list, named control_flow_list and data_flow_list; traverse the PDG, set the current traversal node to be A, if the edge attribute type of the edge from node A to node B is control flow, then take out node A and node B from the dictionary node_dict, form the two nodes into a {A, B} pair, and store them in control_flow_list; similarly, if the edge attribute type of the edge from node A to node B is data flow, then take out node A and node B from the dictionary node_dict, form the two nodes into a {A, B} pair, and store them in data_flow_list;
[0073] The third step is to traverse the control_flow_list and data_flow_list, and delete any self-looping pairs {A,A} if any of them exist;
[0074] The fourth step is to traverse the dictionary node_dict. Assume that the currently traversed node is cur. Note that the next operation is to directly operate on the value in the dictionary node_dict: First, search in the control_flow_list. If there is a {a, cur} pair in the control_flow_list, search for the a node in the dictionary node_dict, and add the node value of the a node to the previous line of the node value of the cur node. For example, the original value of the cur node is "cur_value", and the value of the a node is "a_value". After executing this step, the value of the cur node is "a_value\n cur_value" (\n indicates a line break); if there is a {cur, b} pair in the control_flow_list, search for the b node in the dictionary node_dict, and add the node value of the b node to the next line of the node value of the cur node. For example, the original value of the cur node is "cur_value", and the value of the b node is "b_value". After executing this step, the value of the cur node is "cur_value\n b_value" (\n indicates a line break); Next, search in data_flow_list, the steps are the same as those for control_flow_list;
[0075] Step 5: traverse the dictionary node_dict, obtain the nodes stored in it, which are the nodes of Context-PDG, and replace the nodes of the original PDG with these nodes, which is Context-PDG; Figure 4 is an example of a transformation graph from the original PDG to Context-PDG. Figure 4 In the above, s1, s2, ... etc. represent the node values carried by the nodes, and the values carried by the edges (such as data1, data2, true, false) are marked in the adjacent blocks of the edges;
[0076] Furthermore, all nodes in the Context-PDG are traversed and the value of the node is processed, that is, the value of the node is cut into camel case, cut into snake case, and normalized; the value in the Context-PDG node is actually a code;
[0077] Next, use the value of the Context-PDG node to build a PDG node vocabulary. The PDG node vocabulary consists of "index key-code value", and then store the PDG node vocabulary in the pdg_vocab.pk file;
[0078] Construct a PDG graph embedding layer, which consists of a node embedding layer and an edge embedding layer; map all nodes in PDG through the PDG node vocabulary to obtain the PDG node vector v PDG , then the vector v PDG Through the PDG node embedding layer, we get the node embedding vector v PDG_nodeEmbed ; Use the depth-first algorithm to traverse the PDG and store the edge relationships between nodes in the adjacency matrix. Then, add each node to its own edge, that is, set all the diagonals of the adjacency matrix to 1, and then convert the adjacency matrix to a symmetric matrix. Finally, pass the adjacency matrix through the edge embedding layer to get v PDG_matrix ; The Context-PDG after the graph embedding layer is called the Context-AST modality, denoted as Modal Context-PDG ; In pytorch, the node embedding layer is constructed by torch.nn.Embedding; the edge embedding layer actually converts the adjacency matrix into a tensor, and the code is: torch.Tensor(adjacent), where adjacent is the adjacency matrix;
[0079] S400, constructing a code annotation vocabulary: constructing a code annotation vocabulary using reference annotations in function code-reference annotation pairs in a training set;
[0080] in:
[0081] The specific process of S400 is as follows:
[0082] S410: Process the reference annotation, that is, perform camel case cutting, snake case cutting, and normalization operations on the value of the node;
[0083] S420: Then, a code comment word library is constructed using the processed reference comments, the code comment word library is composed of "index key-code value", and then the code comment word library is stored in the comment_vocab.pk file;
[0084] S500, constructing a multimodal model: constructing a GRU-based encoder GRU_Encoder, a GAT-based encoder GATEncoder_AST, a GAT-based encoder GATEncoder_PDG, and constructing a joint decoder Joint-Decoder;
[0085] in:
[0086] The specific process of constructing the GRU-based encoder GRU_Encoder in S500 is as follows: The encoder GRU_Encoder is used to receive Modal Code-Token , use bidirectional GRU to Modal Code-TokenEncode and generate hidden codeToken as well as After that, the output and embedding vector of GRU are further processed through a fully connected layer, and the encoded representation is finally generated as hi idden codeToken , the process is expressed using the following formula:
[0087]
[0088] in, represents the output encoding representation at time step i, hidden codeToken is the hidden state after BiGRU encoding, Represents the input embedding vector of the i-th step, in fact Modal Code-Token That is The output obtained in the last time step is recorded as Output codeToken ;
[0089] Bidirectional Gated Recurrent Unit (BiGRU) is a variant of recurrent neural network (RNN) specifically designed for processing sequence data. BiGRU is an extension of traditional GRU. By adding a back-propagation GRU, the output of each time step combines the contextual information of the sequence forward and backward at the same time.
[0090] The fully connected layer (FC layer) is a neural network layer that multiplies the input vector by the weight matrix and adds a bias, and outputs the result after being processed by the activation function; it integrates and transforms the input features into new feature representations for learning and prediction in subsequent layers;
[0091] The specific process of constructing the GAT-based encoder GATEncoder_AST and the encoder GATEncoder_PDG in S500 is as follows: The encoder GATEncoder_AST and the encoder GATEncoder_PDG are respectively used to receive Modal VFO-AST Modal Context-PDG , where Modal VFO-AST The steps in the encoder GATEncoder_AST are: Modal VFO-AST After passing through the GAT layer, get Out GAT_AST , and then further processed by a BiGRU layer to capture the contextual information in the graph, and finally get Output GAT_AST ,hidden GAT_AST Similarly, ModalContext-PDG Get Output through encoder GATEncoder_PDG GAT_PDG ,hidden GAT_PDG ;
[0092] The specific process of constructing the joint decoder in S500 is as follows:
[0093] Process 1: Joint-Decoder receives Output codeToken 、hidden codeToken 、Output GAT_AST 、hidden GAT_AST , Ouput GAT_PDG and hidden GAT_PDG , use the attention mechanism to calculate the Output separately codeToken 、Output GAT_AST and Output GAT_PDG The attention weights are obtained. AttnCT 、Out AttnVAST and Out AttnCPDG ;
[0094] The calculation formula of its attention score is:
[0095]
[0096] Among them, h t is the hidden state of the decoder at time t. When t = 0, hidden codeToken ,s i is the ith hidden state of Output, W a and v a is a learnable parameter, Indicates v a The transpose of the current hidden state h t The user can choose according to the actual situation. In this invention, after debugging, the hidden codeToken As h t The effect is the best; for the convenience of expression, the present invention will Output codeToken 、Output GAT_AST and Output GAT_PDG Abbreviated as Output;
[0097] The calculation formula of its attention weight is:
[0098]
[0099] Among them, T is the length of the sequence corresponding to Output, α tirepresents the attention weight of the decoder on the i-th hidden state of Output at time step t, and exp() is an exponential function;
[0100] Process 2: Out AttnCT and Out AttnVAST Perform weighted addition and then add it to Out AttnCPDG Perform vector concatenation to get Out JointVector ;
[0101] The steps for obtaining the weight of weighted addition are as follows: first, codeToken and hidden GAT_AST After splicing, we get h t , and then h t The weight coefficient gridWeight is obtained through the softmax layer, linear layer and sigmoid layer respectively. The calculation formula of the weight coefficient gridWeight is:
[0102] gridWeight=Sigmoid(Linear(softmax(h t )));
[0103] Vector concatenation can be implemented in pytorch using torch.cat;
[0104] Softmax layer: converts logits into probability distribution, often used for multi-classification problems;
[0105] Linear layer: performs linear transformation on the input for feature extraction and output prediction;
[0106] Sigmoid layer: maps the input to between 0 and 1, often used for binary classification problems or as an activation function;
[0107] Process 3: Out JointVector After passing into the GRU-based decoder, it passes through a Linear layer to obtain the vocabulary distribution vector V wordDis , use greedy decoding to convert V wordDis Decode step by step to obtain a series of code comment indexes, and map them to the code comment vocabulary to obtain code comments;
[0108] Greedy Decoding is a simple method for selecting the most likely next element in sequence generation tasks. At each step, greedy decoding selects the output with the highest probability under the current conditions, thereby gradually building up the entire output sequence.
[0109] S600, model training: the training set and validation set are used for model training, and the test set is used to evaluate model performance;
[0110] in:
[0111] The specific process of S600 is as follows: Use Modal Code-Token Modal VFO-AST Modal Context-PDG Training the network model architecture includes: Code-Token Modal VFO-AST Modal Context-PDG Input the initial function annotation generation model, generate the corresponding training function code annotation, and then calculate the loss value between the function code annotation generated by the training function code and the associated reference annotation. The training goal is to make the generated annotation most similar to the reference annotation. Select CrossEntropyLoss as the loss function. The formula of the loss function Loss is:
[0112]
[0113] Where p is the predicted annotation, y is the reference annotation, T is the length of the reference annotation sequence, and y t is the reference vocabulary at time step t, is the model's prediction of the reference vocabulary y at time step t t The predicted probability of
[0114] Then, a threshold is set for the training loss value. First, the number of consecutive loss calculation rounds m and the standard threshold threshold are determined. The parameters are determined by the model trainer according to the actual situation. The average loss value of m rounds is calculated continuously, and the difference between the average loss value of the current round and the loss value of the previous round is compared. If the absolute value of all these differences is less than the threshold, the training is stopped and the multimodal network model is generated; otherwise, the parameters of the encoder and decoder are automatically adjusted according to the preset gradient;
[0115] S700, generating target code function annotations: when receiving target code function data, performing function code preprocessing operations on it, and using a multimodal network model to generate corresponding target code function annotations.
[0116] The advantages of the present invention are:
[0117] First, use the valueless optimization AST algorithm to simplify the AST structure, effectively reduce redundant nodes, improve the simplicity and clarity of the tree structure, and help improve the training efficiency and performance of the model.
[0118] Second, the contextual PDG information enhancement algorithm is used to enrich the information carried by PDG nodes. By integrating the contextual information of control flow and data flow, the expressiveness and contextual relevance of the nodes are enhanced, effectively improving the model's understanding and accuracy of code semantics and dependencies.
[0119] Third, by integrating different code information sources, including vocabulary information, optimized AST structure and PDG information with context, we can deeply understand and accurately analyze function codes, significantly improving the quality and comprehensiveness of generated code comments.
[0120] Although the present invention has been described above with reference to the embodiments, various modifications may be made thereto and parts thereof may be replaced by equivalents without departing from the scope of the present invention. In particular, as long as there is no structural conflict, the various features in the embodiments disclosed in the present invention may be used in combination with each other in any manner, and the fact that these combinations are not exhaustively described in this specification is only for the sake of omitting space and saving resources. Therefore, the present invention is not limited to the specific embodiments disclosed herein, but includes all technical solutions falling within the scope of the claims.
Claims
1. A method for generating code comments based on syntax optimization and context enhancement, characterized in that: The specific steps are as follows: S100, constructing function code / reference annotation pairs: constructing function codes in the data set and their corresponding reference annotations into function code / reference annotation pairs, and then all function code-reference annotation pairs constitute a function code-reference annotation pair data set; S200, split the data set: After shuffling the data set, split it into a training set, a validation set, and a test set, ensuring that the three subsets are independent of each other and do not overlap; S300, function code preprocessing: including normalizing the code, generating PDG and AST, and then using corresponding methods to generate Code-Token mode, Context-PDG mode and VFO-AST mode; S400, constructing a code annotation vocabulary: constructing a code annotation vocabulary using reference annotations in function code-reference annotation pairs in a training set; S500, constructing a multimodal model: constructing a GRU-based encoder GRU_Encoder, a GAT-based encoder GATEncoder_AST, a GAT-based encoder GATEncoder_PDG, and constructing a joint decoder Joint-Decoder; S600, model training: the training set and validation set are used for model training, and the test set is used to evaluate model performance; S700, generating target code function annotations: when receiving target code function data, performing function code preprocessing operations on it, and using a multimodal network model to generate corresponding target code function annotations.
2. A method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The Code-Token modal generation process in S300 is as follows: the camel case words in the function code are cut according to the camel case naming rule, and then the snake case words in the function code are cut according to the snake case naming rule, and then the code is normalized. The normalization operation includes: adding spaces between words, between words and punctuation marks, and between punctuation marks in the function code to ensure that words and punctuation marks are regarded as independent entities. Then, the code after the above processing is used to build a code vocabulary, which is composed of "index key-code value", and then the code vocabulary is stored in the code_vocab.pk file. Then, a code token embedding layer is built, and the preprocessed code is mapped through the code vocabulary to obtain a code vector v code-token , then the vector v code-token After the code vocabulary embedding layer, the Code-Token modality is obtained, denoted as Modal Code-Token .
3. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The VFO-AST modal generation process in S300 is as follows: use an abstract syntax tree generation tool to generate the corresponding AST from the function code, and the information carried in each node in the obtained AST includes: node type type, node value value, and node subtree set children.
4. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The Context-PDG modality generation process in S300 is as follows: use the program dependency graph generation tool to generate the corresponding PDG from the function code, recorded as the original PDG, and the information carried by each node in the obtained original PDG includes: node type type, node value value, node subtree set children, and the information carried by each edge in the PDG includes: edge attribute type, edge start node, and edge end node.
5. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The specific process of S400 is as follows: S410: Process the reference annotation, that is, perform camel case cutting, snake case cutting, and normalization operations on the value of the node; S420: Then use the processed reference comments to build a code comment vocabulary, the code comment vocabulary is composed of "index key-code value", and then store the code comment vocabulary in the comment_vocab.pk file.
6. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The specific process of constructing the GRU-based encoder GRU_Encoder in S500 is as follows: The encoder GRU_Encoder is used to receive Modal Code-Token , use bidirectional GRU to Modal Code-Token Encode and generate hidden codeToken as well as After that, the output and embedding vector of GRU are further processed through a fully connected layer, and the encoded representation is finally generated as The process is expressed using the following formula: in, represents the output encoding representation at time step i, hidden codeToke n is the hidden state after BiGRU encoding, Represents the input embedding vector of the i-th step, in fact Modal Code-Token That is The output obtained in the last time step is recorded as Output codeToken .
7. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The specific process of constructing the GAT-based encoder GATEncoder_AST and the encoder GATEncoder_PDG in S500 is as follows: The encoder GATEncoder_AST and the encoder GATEncoder_PDG are respectively used to receive Modal VFO-AST Modal Context-PDG , where Modal VFO-AST The steps in the encoder GATEncoder_AST are: Modal VFO-AST After passing through the GAT layer, get Out GAT_AST , and then further processed by a BiGRU layer to capture the contextual information in the graph, and finally get Output GAT_AST ,hidden GAT_AST Similarly, Modal Context-PDG Get Output through encoder GATEncoder_PDG GAT_PDG ,hidden GAT_PDG .
8. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The specific process of constructing the joint decoder in S500 is as follows: Process 1: Joint-Decoder receives Output codeToken 、hidden codeToken 、Output GAT_AST 、hidden GAT_AST 、Output GAT_PDG and hidden GAT_PDG , use the attention mechanism to calculate the Output separately codeToken 、Output GAT_AST and Output GAT_PDG The attention weights are obtained. AttnCT 、Out AttnVAST and Out AttnCPDG ; The calculation formula of its attention score is: Among them, h t is the hidden state of the decoder at time t. When t = 0, hidden codeToken ,s i is the ith hidden state of Output, W a and v a is a learnable parameter, Indicates v a The transpose of The calculation formula of its attention weight is: Among them, T is the length of the sequence corresponding to Output, α ti represents the attention weight of the decoder on the i-th hidden state of Output at time step t, and exp() is an exponential function; Process 2: Out AttnCT and Out AttnVAST Perform weighted addition and then add it to Out AttnCPDG Perform vector concatenation to get Out JointVector ; The steps for obtaining the weight of weighted addition are as follows: First, hidden codeToken and hidden GAT_AST After splicing, we get h t , and then h t The weight coefficient gridWeight is obtained through the softmax layer, linear layer and sigmoid layer respectively. The calculation formula of the weight coefficient gridWeight is: gridWeight=Sigmoid(Liner(softmax(h t ))); Process 3: Out JointVector After passing into the GRU-based decoder, it passes through a Linear layer to obtain the vocabulary distribution vector V wordDis , use greedy decoding to convert V wordDis A series of code comment indexes are obtained by step-by-step decoding, and the code comments are obtained by mapping the indexes to the code comment vocabulary.
9. The method for generating code comments based on syntax optimization and context enhancement according to claim 1, characterized in that: The specific process of S600 is as follows: Use Modal Code-Token Modal VFO-AST Modal Context-PDG Training the network model architecture includes: Code-Token Modal VFO-AST Modal Context-PDG Input the initial function annotation generation model, generate the corresponding training function code annotation, and then calculate the loss value between the function code annotation generated by the training function code and the associated reference annotation. The training goal is to make the generated annotation most similar to the reference annotation. Select CrossEntropyLoss as the loss function. The formula of the loss function Loss is: Where p is the predicted annotation, y is the reference annotation, T is the length of the reference annotation sequence, and y t is the reference vocabulary at time step t, is the model's prediction of the reference vocabulary y at time step t t The predicted probability of Then set a threshold for the training loss value. First, determine the number of consecutive loss calculation rounds m and the standard threshold threshold. The parameters are determined by the model trainer based on actual conditions. Calculate the average loss value of m rounds in succession, and compare the difference between the average loss value of the current round and the loss value of the previous round. If the absolute values of all these differences are less than the threshold, stop training and generate a multimodal network model; otherwise, automatically adjust the parameters of the encoder and decoder according to the preset gradient.
Citation Information
Patent Citations
Code annotation generation method based on multiple source code representation and recurrent neural network
CN114816516A
Code annotation generation method based on pre-training model and space structure information
CN115469925A
Code annotation generation method and system
CN115543437A
Automatic annotation generation method based on multi-modal code representation
CN115756597A
Model training method and device, code submission annotation generation method and device and electronic equipment
CN116737228A
