Method for performing efficient parameter fine tuning on code model in combination with abstract syntax tree
By converting code snippets into abstract syntax trees and using graph neural networks to extract structured representations and perform efficient parameter fine-tuning, the problem of insufficient adaptability of code models in code tasks in the existing technology is solved, and implementation of various code tasks is achieved. performance improvement and resource saving.
Patent Information
- Application Number
- CN202410868774.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-01
- Publication Date
- 2024-10-01
- Estimated Expiration
- 2044-07-01
AI Technical Summary
Existing efficient parameter fine-tuning methods are mainly aimed at natural language processing tasks and do not fully consider the particularity of the code, especially the strict grammatical rules and hierarchical structure of the code, resulting in insufficient model adaptation capabilities for code tasks.
By converting code snippets into abstract syntax trees (AST), and then converting the AST into graph structures, using graph neural networks to extract structured representations and using them as adapter modules with pre-trained code models for efficient parameter fine-tuning, only updating the adapter parameters of the module, freezing the rest of the code model.
It significantly improves the performance of the code model on code tasks, reduces training resources and time costs, and is suitable for a variety of downstream code tasks, such as code summary, code translation and vulnerability detection.
Smart Images

Figure CN118733052A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the application of deep learning models in code scenarios, and in particular to a method for fine-tuning code models by combining efficient parameters with an abstract syntax tree. Background Art
[0002] With the rapid development of deep learning technology, many large pre-trained models have emerged in the code field, such as CodeT5, CodeBERT, etc. These models have demonstrated powerful capabilities in code understanding and generation tasks, and can be used in a variety of application scenarios such as code summarization, code generation, defect detection, quality analysis, code refactoring, and code translation. The emergence of code models has greatly improved the efficiency of software development and maintenance, and promoted the improvement of code quality and maintainability.
[0003] Although the current code model already has relatively general software development capabilities, in practical applications, it is often necessary to fine-tune for specific tasks to further improve the adaptability of the model. Traditional fine-tuning methods usually require updating all parameters of the model, which is time-consuming and requires a lot of training data and computing resources. In order to solve this problem, researchers have proposed the idea of efficient parameter fine-tuning, that is, fixing most of the parameters in the model and only fine-tuning a small number of parameters to achieve the purpose of rapid adaptation to different tasks. Efficient parameter fine-tuning methods have been widely used in the field of natural language processing, such as Prompt-Tuning, Prefix-Tuning, LoRA, etc. These methods can significantly reduce the data, time and computing resources required for fine-tuning while maintaining high performance. For example, a Chinese patent with publication number CN118132674A discloses a text information extraction method based on a large language model and efficient parameter fine-tuning: using the powerful text understanding and generalization capabilities of the large language model, different information extraction tasks are modeled as natural language inputs, and their output space and output format are restricted, and then the output of the model is converted into structured information through simple processing; from the perspective of model training, through the efficient parameter fine-tuning method, by fine-tuning a very small number of parameters, the model can adapt to the information extraction task while retaining its original language understanding and generalization capabilities. Compared with the full parameter training method, it has the same or even better effect, but only requires very little computing resources and training time; from the perspective of generalization ability, since the generalization ability of the model is retained to a great extent, this method performs better than previous methods in low resources and new labels, and is more suitable for practical applications.
[0004] However, the existing efficient parameter fine-tuning methods are mainly aimed at natural language processing tasks, and do not fully consider the particularity of the code. Unlike natural language, the code has strict grammatical rules and hierarchical structure. These structural information can be represented by an abstract syntax tree (AST). Studies have shown that introducing the code structure features contained in the AST into the code model can significantly improve the performance of the model in code understanding and generation tasks. For example, the Chinese patent with publication number CN113420296 A discloses a software defect prediction method and terminal based on a graph convolutional neural network, including: uniformly processing a data set composed of code files, parsing it into an abstract syntax tree, adjusting the structure of the abstract syntax tree and retaining the key information of the nodes; constructing the adjusted abstract syntax tree into a graph structure to construct a training set; training to obtain a first prediction model, inputting the data to be predicted to obtain a first defect tendency result; training to obtain a second prediction model, inputting the data to be predicted to obtain a second defect tendency result; averaging the two values as the final defect prediction result.
[0005] Therefore, how to design an efficient parameter fine-tuning method that integrates code structure information to better improve the adaptability of existing code models in downstream tasks has become an urgent problem to be solved. Summary of the invention
[0006] The purpose of the present invention is to provide a method for efficiently fine-tuning a code model by combining an abstract syntax tree with parameters, which can significantly improve the performance of the code model on various code tasks while reducing the amount of fine-tuning parameters.
[0007] The present invention is achieved through the following technical solutions:
[0008] A method for efficiently fine-tuning a code model by combining an abstract syntax tree with parameters, the method comprising the following steps:
[0009] S1. Data collection and preprocessing: Collect code snippets as training data and test data;
[0010] S2, automatic construction of abstract syntax tree: automatically analyze the code snippet and convert it into an abstract syntax tree AST containing code structure and syntax information;
[0011] S3, converting the abstract syntax tree into a graph structure: converting the abstract syntax tree into a graph data structure, and constructing a graph structure containing node and edge relationships;
[0012] S4, graph structure embedding: digitize the graph structure through dimensionality reduction embedding technology to generate an abstract syntax tree embedding vector;
[0013] S5, graph neural network construction: using the edge relationship of the graph structure in step S3 and the embedding vector in step S4 as the input of the graph neural network, learning the structured representation of the code snippet, and obtaining the constructed graph neural network;
[0014] S6. Fine-tuning of code model parameters: Use the constructed graph neural network as an adapter module, use the training data of step S1 to train the pre-trained code model, and perform efficient parameter fine-tuning during the training process to obtain a fine-tuned code model.
[0015] The step S1 includes: arranging the training data and the test data into different data formats according to different downstream tasks, and cleaning and preprocessing the training data and the test data, wherein the preprocessing includes:
[0016] S1.1, filter invalid and duplicate code snippets;
[0017] S1.2, remove redundant information in the code snippet;
[0018] S1.3. Format the code.
[0019] The data formats of the different tasks are specifically as follows:
[0020] (1) Code summary task: <code snippet, corresponding natural language summary>;
[0021] (2) Code translation task: <source code, target language code>;
[0022] (3) Vulnerability detection task: <code snippet, whether there is a specific vulnerability>.
[0023] The redundant information in step S1.2 includes comments, blank lines, etc.
[0024] The process of automatically constructing the abstract syntax tree in step S2 includes:
[0025] S2.1, load the syntax file of a specific programming language;
[0026] S2.2. Parse the code snippet using the grammar rules defined in the grammar file to generate an abstract syntax tree;
[0027] S2.3. Merge and delete redundant branch nodes and leaf nodes in the abstract syntax tree to obtain a simplified abstract syntax tree.
[0028] In step S3, the method of converting the abstract syntax tree into a graph structure is:
[0029] S3.1. Use the root node of the abstract syntax tree as the starting node of the graph structure;
[0030] S3.2, traverse the abstract syntax tree:
[0031] S3.2.1. Map each node in the abstract syntax tree to a node of the graph structure and record the node type information;
[0032] S3.2.2, map the relationship between each node in the abstract syntax tree and its parent node and child node into a directed edge of the graph structure as an edge relationship;
[0033] S3.3. Prune the graph structure, remove redundant nodes and directed edges, and generate the final graph structure.
[0034] Preferably, converting the abstract syntax tree into a graph structure mainly includes the following steps:
[0035] a) Define a graph structure G(N, E). N represents the set of nodes in the graph, and each node corresponds to a node in the original tree structure. E represents the set of edges in the graph, and each edge represents the relationship between nodes. In the tree structure, each node (except the root node) has only one parent node and can have several child nodes.
[0036] b) Map each node in the tree structure to a node in the graph structure. If there are m nodes in the tree structure, then the converted graph structure G will also contain m nodes, that is, |N|=m.
[0037] c) Map each edge in the tree structure to a unidirectional edge in the graph structure. In the tree structure, each node (except the root node) has a parent node and may have multiple child nodes. For each parent-child node pair, convert it into an edge in the graph, which points from the graph structure node corresponding to the parent node in the tree structure to the graph structure node corresponding to the child node in the tree structure. The edge set E in the graph structure will contain all the edges corresponding to these parent-child relationships.
[0038] The graph structure embedding in step S4 includes:
[0039] S4.1 performs word segmentation on the types of nodes and source code symbols in the graph structure;
[0040] S4.2 expands the vocabulary of the pre-trained code model, adds new node types and symbols to the vocabulary, and obtains a word vector matrix of the pre-trained code model;
[0041] S4.3 Use the word vector matrix of the pre-trained code model to initialize the node embedding vector after word segmentation in the graph structure;
[0042] S4.4 combines the node embedding vectors after word segmentation of each node into a node embedding vector by averaging or weighted summing.
[0043] In step S5, the present invention constructs a graph neural network (GNN) as an adapter module of the code model, and uses various neighborhood aggregation strategies to explicitly incorporate the graph structure into the code model. The specific steps include: using the edge relationship of the graph structure in step S3 and the embedding vector in step S4 as the input of the GNN; secondly, the GNN aggregates each node in the graph structure and its neighborhood information to reflect its position in the graph structure and the characteristics of its neighbors; finally, by stacking multiple GNN layers, the node representation can capture more distant neighborhood information, thereby enhancing the representation ability of the graph neural network and further enhancing the ability of the graph neural network to adapt to the code model.
[0044] As a further improvement, the present invention considers that different graph neural networks have different representation capabilities and may be suitable for different downstream code tasks. The present invention respectively embeds graphs with various graph neural networks to learn abstract code semantics. The main graph neural networks used are:
[0045] Graph Convolutional Network (GCN): GCN aggregates the information of neighbors by performing convolution operations directly on the graph. It uses a normalized Laplacian matrix to achieve weighted averaging of information, effectively capturing the local graph structure of the node.
[0046] Graph Attention Network (GAT): GAT introduces an attention mechanism to dynamically determine the importance of each neighbor when aggregating neighbor node information. This allows the model to capture complex relationships between nodes more flexibly.
[0047] GraphSage: GraphSage is designed for large-scale graph data by sampling a fixed-size neighborhood and then aggregating the information of these neighbors to update the representation of the target node. This approach is both efficient and scalable.
[0048] The method of efficient parameter fine-tuning in step S6 is:
[0049] S6.1. Load the pre-trained code model;
[0050] S6.2, using the graph neural network constructed in step S5 as an adapter module, and connecting it to the pre-trained code model through soft prompting or prefix tuning;
[0051] S6.3. On the training data of the downstream task, only fine-tune the adapter module parameters in the code model and freeze the rest of the code model.
[0052] Among them, the soft prompt fine-tuning method can also be called the prompt word fine-tuning method. Specifically, the output of the graph neural network described in step S5 is used as the prompt word, and the output of the code model and downstream tasks is guided by the prompt word fine-tuning method. This strategy enables the model to adapt to different downstream task requirements more accurately and improve task specificity.
[0053] Preferably, in step S6.2, the soft hint fine-tuning method is as follows: insert the vector output of the graph neural network as a "soft hint" at the input end of the pre-trained code model, and concatenate the "soft hint" with the text embedding vector of the source code fragment as the input of the encoder in the code model; in the fine-tuning stage, only the parameters of the vector of the graph neural network are updated, and the rest of the code model is frozen.
[0054] The source code fragment after word segmentation is encoded using the same word vector matrix as in step S4.3 to obtain a text embedding vector of the source code fragment;
[0055] Preferably, in step S6.2, the prefix fine-tuning method is: in each multi-head attention layer (Multi-Head Attention Layer) of the encoder and decoder of the code model, a learnable prefix vector is introduced, and the introduction method is: the output of the graph embedding module is used as the prefix vector, and the key value matrix of the multi-head attention layer is spliced. That is, the present invention introduces prefix fine-tuning in the Transformer structure of the code model, and uses the output of the graph neural network as a learnable prefix vector to adjust the prefix weight of the KV matrix in each attention layer.
[0056] In step S6, the efficient parameter fine-tuning process is specifically manifested in that during the gradient back-propagation process, only the gradient information of the adapter module is updated, and the gradient information of the code model is not updated. This parameter update method can efficiently adapt the model to different downstream code tasks, such as code summarization tasks, code translation tasks, vulnerability detection tasks, etc.
[0057] As a further improvement, for each different downstream code task, the present invention can train a specific code adapter through the data set collected and processed in step S1 to improve the effect of the specified code task.
[0058] The present invention also provides an application of a code model obtained according to the above method to a code task.
[0059] The code tasks are:
[0060] Code summarization task: input code snippets into the model and decode them to generate corresponding natural language descriptions;
[0061] Vulnerability detection task: input code snippets into the model, decode and generate vulnerability types or vulnerability existence probabilities;
[0062] Code translation task: input source code into the model and decode it to generate code in the target language.
[0063] The beneficial effects of the present invention are as follows:
[0064] The present invention proposes a method for fine-tuning code models by combining abstract syntax trees with efficient parameters for large models in the field of code. The method is based on multiple open source code task data sets, collects and classifies different code task data sets, automatically generates abstract syntax trees corresponding to each data set, and uses graph neural networks to combine the abstract syntax trees into the code large model in the form of adapters, and trains the large model in the form of efficient parameter fine-tuning, so that the code large model is suitable for multiple more downstream code application scenarios. The present invention utilizes the unique structural information in the code text, introduces AST into the code model by introducing graph neural networks as adapter modules, fully mines and utilizes the structured features of the code, and improves the model's understanding and representation capabilities of the code; provides a framework combining pluggable GNN adapter modules with code models, which can flexibly adapt to a variety of different graph neural networks, and further adapt to the needs of multiple downstream code tasks; adopts an efficient parameter fine-tuning strategy, and only updates the parameters of a small number of adapter modules during the fine-tuning process, which greatly reduces the required training resources and time costs, and significantly improves the performance of the code model on downstream tasks, which has important theoretical and practical significance.
[0065] Compared with existing fine-tuning methods (such as Prefix Tuning), the efficient parameter fine-tuning code model provided by this method has significant performance improvements on code tasks in multiple programming languages. For example, in the code summarization task, measured by the BLEU4 indicator, the performance improvement of the prefix fine-tuning method combined with AST in the present invention on programming languages such as Ruby, Javascript, Go, PHP, Python, etc. is between 0.72% and 4.36%. In other downstream code tasks, the efficient fine-tuning large model proposed in the present invention has improved performance. In summary, the method of combining efficient parameter fine-tuning code models with AST proposed in the present invention makes full use of the structured information of the code, introduces a flexible graph neural network in the form of an adapter, and adopts an efficient fine-tuning strategy, which significantly improves the performance of the code model on multiple downstream tasks while reducing resource overhead, and has significant technical advantages and practical value. BRIEF DESCRIPTION OF THE DRAWINGS
[0066] Figure 1 A flowchart of a method for efficiently fine-tuning a code model by combining an abstract syntax tree with parameters provided by the present invention;
[0067] Figure 2A structural flow chart of a method for efficiently fine-tuning a code model by combining an abstract syntax tree with high-efficiency parameters provided by the present invention;
[0068] Figure 3 An example diagram of converting source code into a simplified abstract syntax tree. DETAILED DESCRIPTION
[0069] The specific technical scheme of the present invention is further described below in conjunction with the accompanying drawings:
[0070] The present invention is realized by the following technical scheme: first, collect training data and evaluation data on open source websites; then, construct an abstract syntax tree related to the data set through an automated process; secondly, convert the abstract syntax tree into a graph structure; then convert the graph structure into a graph embedding through an embedding vocabulary; at the same time, construct a graph neural network model, and combine the graph neural network into the code model as an adapter module; finally, train the code model by efficient parameter fine-tuning, and efficiently adapt to various code tasks according to the adapter module, such as code summarization tasks, code translation tasks, vulnerability detection tasks, etc. This method utilizes the structured information in the code, and quickly obtains a fine-tuning model with superior performance through limited training resources, data resources, and time costs, which is suitable for multiple downstream code application scenarios, including but not limited to code document generation, code translation, vulnerability detection, etc.
[0071] like Figure 1 and Figure 2 As shown, the flowchart of the method for efficiently fine-tuning a code model by combining an abstract syntax tree provided in this embodiment includes the following steps:
[0072] S1: Organize the training data and test data into different data formats according to different downstream tasks, and clean and preprocess the training data and test data:
[0073] Preprocessing includes:
[0074] S1.1, filter invalid and duplicate code snippets;
[0075] S1.2. Remove redundant information (including comments, blank lines, etc.) from code snippets.
[0076] S1.3. Format the code.
[0077] In this embodiment, first, the data set required for training and evaluating (testing) the code model is collected on an open source code platform, such as Github (one of the world's largest code hosting platforms). The data is obtained by crawling code snippets and using existing data sets. After collecting and integrating into an original data set, the above original data set is processed. The data processing process includes filtering meaningless samples and removing meaningless characters. Finally, according to different downstream tasks, the collected data sets are classified and divided into code summary data sets, code translation data sets, and vulnerability detection data sets.
[0078] Each data entry in each dataset consists of two parts, and the data format is as follows: for the code summary dataset, the data format is <code snippet, corresponding natural language summary>; for the code translation dataset, the data format is <source code, target language code>; for the vulnerability detection dataset, the data format is <code snippet, whether there is a specific vulnerability>.
[0079] S2. Automatic construction of abstract syntax tree: Automatically analyze the code snippets and convert them into abstract syntax trees (ASTs) containing code structure and syntax information:
[0080] S2.1, load the syntax file of a specific programming language;
[0081] S2.2. Parse the code snippet using the grammar rules defined in the grammar file to generate an abstract syntax tree;
[0082] S2.3. Merge and delete redundant branch nodes and leaf nodes in the abstract syntax tree to obtain a simplified abstract syntax tree.
[0083] In this embodiment, the code portion of the collected data set is converted into an abstract syntax tree through the tool Treesitter. Treesitter is an open source generator tool that uses the grammatical rules of the programming language to generate an abstract syntax tree. The abstract syntax tree uses a tree structure to display the grammatical structure of the source code, where each node in the tree represents a part of the code, such as an expression, statement, operator, etc. This tree-like representation allows the serialized code to show deep structural information, allowing development tools and systems to understand and operate the code more intelligently. In the present invention, the abstract syntax structure can help the model better understand the code semantic information. After conversion to an abstract syntax tree (AST), the AST is further parsed to generate a simplified version of the AST suitable for graph neural networks.
[0084] In step S2.3: Based on the above-mentioned abstract syntax tree, measures are taken to delete redundant nodes in the syntax tree to generate a further simplified version of the abstract syntax tree. The generation steps of the simplified abstract syntax tree include the following three stages: First, the leaf nodes that do not carry semantic information in the abstract syntax tree are cleared, such as semicolons, left brackets, right brackets, etc.; for non-leaf nodes, only non-leaf nodes with strong structural information are retained, that is, only nodes containing program execution flow information and variable declaration information are retained, such as "Declaration", "Statement", "Call", "Block" nodes; for deleted non-leaf nodes, their parent nodes and child nodes are connected to form a new simplified abstract syntax tree. This simplified abstract syntax tree reduces the dimension of the graph neural network while retaining key semantic information.
[0085] S3. Convert the abstract syntax tree into a graph structure: Convert the abstract syntax tree into a graph data structure and construct a graph structure containing node and edge relationships:
[0086] Use breadth-first search to traverse the AST generated by Treesitter, and apply a queue data structure to save node information, including:
[0087] S3.1. Initialize the node list, edge list and leaf node ID list.
[0088] S3.2. Add the root node to the queue, and the elements in the queue are tuples (parent_id, node).
[0089] S3.3. For leaf nodes, obtain the corresponding source code and add it to the node list and leaf node ID list.
[0090] S3.4. For non-leaf nodes, add the node type to the node list.
[0091] S3.5. Add a bidirectional edge between the current node and the parent node to the edge list.
[0092] Through the above steps, the source code can be converted into an AST representation that is easy to process and analyze. On this basis, the nodes are encoded and truncated to meet the needs of further code analysis and processing tasks. Figure 3 An application example is demonstrated, the source code for finding the maximum value of two numbers is given, and the corresponding AST structure generated by this method is shown, including a node list, an edge list, and a leaf node ID list, to facilitate further code analysis.
[0093] S4. Graph structure embedding: The graph structure is digitized through dimensionality reduction embedding technology to generate an abstract syntax tree embedding vector:
[0094] S4.1. Perform word segmentation on the types of nodes and source code symbols in the graph structure;
[0095] S4.2, expanding the vocabulary of the pre-trained code model, adding new node types and symbols to the vocabulary, and obtaining the word vector matrix of the pre-trained code model;
[0096] S4.3. Use the word vector matrix of the pre-trained code model to initialize the node embedding vector after word segmentation in the graph structure;
[0097] S4.4. Combine the node embedding vectors after word segmentation of each node into a node embedding vector by averaging or weighted summing.
[0098] The present invention converts each node in the graph structure represented by a string into a continuous, fixed-length vector. In this embodiment, the above embedding process specifically includes the following steps:
[0099] a) Use the same tokenizer as the code model to decompose the variable names and keywords of the graph structure nodes into more fine-grained subtokens.
[0100] b) Convert the above sub-tokens into vector form using the same embedding matrix as the code model. This step encodes each sub-token into a fixed-length continuous vector that captures its semantic and syntactic features in the code.
[0101] c) By summing up the vectors of each sub-token in the same graph structure node, a synthetic embedding vector representing the original node of the graph structure is constructed. This synthetic embedding vector inherits the information of all the sub-tokens that make it up and provides a comprehensive graph structure node representation for further code analysis and processing.
[0102] S5, graph neural network construction: Use the edge relationship of the graph structure in step S3 and the embedding vector in step S4 as the input of the graph neural network, learn the structured representation of the code snippet, and obtain the constructed graph neural network:
[0103] S5.1. According to the graph structure of S4, use the embedding module in the code model to process the strings in the graph nodes, generate vectors as the embedding representation of the graph nodes, and use the embedding representations of all nodes and the edge relationships between nodes as the input of the graph neural network;
[0104] S5.2. Define the graph neural network encoder GraphEncoder; initialize all graph neural network layers and determine the number of graph neural network layers N according to the configuration parameters; select the graph convolution type according to the configuration parameters, considering that different graph neural networks have different representation capabilities and may be suitable for different downstream code tasks. The optional types are GCN, GraphSAGE, and GAT;
[0105] S5.3. For the first N-1 layers, use the selected graph convolution type module to perform graph convolution operations on node features and apply the ELU activation function; by aggregating each node in the graph structure and its neighborhood information to reflect its position in the graph structure and the characteristics of its neighbors;
[0106] S5.4. For the last layer, use the DenseDiffpool module to perform graph convolution on the node features and use the differentiable pooling method to pool the graph to generate the final virtual node representation;
[0107] S5.5 stacks multiple graph neural network layers to enable node representation to capture more distant neighborhood information, thereby enhancing the representation capability of the graph neural network and further enhancing the ability of the graph neural network to adapt to code models.
[0108] Through the above steps, the method provided by the present invention uses the code large model embedding module to embed the graph structure, then uses the graph neural network to encode the input, extracts node features through multi-layer graph convolution operations, and uses the differentiable pooling method to pool the graph to generate the final virtual node representation. By explicitly incorporating graph structure information into the code model and using various neighborhood aggregation strategies, the ability of the graph neural network to adapt to the code model is enhanced.
[0109] S6. Fine-tuning of code model parameters: Use the constructed graph neural network as an adapter module, use the training data of step S1 to train the pre-trained code model, and perform efficient parameter fine-tuning during the training process to obtain a fine-tuned code model:
[0110] S6.1. Load pre-trained code models: Use the huggingface / transformer open source framework to download and load pre-trained code models, such as CodeT5, CodeLlama, etc.
[0111] S6.2, using the graph neural network constructed in step S5 as an adapter module, and connecting it to the pre-trained code model through soft prompts or prefix fine-tuning;
[0112] Use prompt tuning to introduce the graph embedding module: embed the code graph
[0113] It is represented as a soft prompt and concatenated with the original embedding of the code as the final input of the model;
[0114] The output of the graph embedding module is used as a soft prompt and added to the encoder’s input sequence. Use prefix tuning to introduce the graph embedding module:
[0115] A learnable prefix vector is introduced into each multi-head attention layer of the decoder; the output of the graph embedding module is used as the prefix vector and concatenated with the key-value matrix of the attention layer.
[0116] S6.3. On the training data of the downstream task, only fine-tune the adapter module parameters in the code model and freeze the rest of the code model.
[0117] Wherein, in step S6.3:
[0118] According to the task data set collected and processed in the previous step, the code model combined with the graph embedding module is fine-tuned. Specifically, the present invention uses the optimization algorithm AdamW and sets hyperparameters (learning rate is 1e-5, batch size is 16) for training.
[0119] During the fine-tuning process, an efficient parameter fine-tuning strategy is used to reduce the number of parameters that need to be updated. Specifically, all parameters of the pre-trained code model are frozen, and only the parameters of the graph embedding module are fine-tuned. The final fine-tuned parameters account for only a small part of all parameters (less than 5%). The implementation method of freezing parameters is to only calculate the gradient during the back-propagation process without updating the parameters of the code model.
[0120] During the training process, the efficient parameter fine-tuning module parameters are saved based on the effect on the validation dataset.
[0121] S7. Reasoning evaluation: After training is completed, use the adapter model parameters saved in the efficient parameter fine-tuning stage to perform reasoning and performance evaluation on the model on the evaluation dataset (downstream task adaptation: use the fine-tuned model to perform fine-tuning and evaluation on downstream tasks such as code summarization, vulnerability detection, and code translation to verify the model's adaptability to different tasks). The specific steps are as follows:
[0122] S7.1. Model initialization and loading: This embodiment first initializes a new model instance and loads the pre-trained code model parameters as the initial weights of the model backbone network; secondly, it loads the adapter module parameters learned in the efficient parameter fine-tuning phase, including the weights of the graph neural network and soft prompt / prefix vector; finally, the adapter module is combined with the pre-trained model backbone to build a complete inference model.
[0123] S7.2, Model Reasoning: First, according to the task type, convert the evaluation data set into an input format acceptable to the model: for code summarization tasks, convert code snippets into the model's encoder input; for code translation tasks, convert source code into encoder input, and target code into decoder output; for vulnerability detection tasks, convert code snippets into encoder input. Secondly, use the constructed reasoning model to reason on the evaluation data and decode the output to get the corresponding result: for code summarization tasks, decoding generates the corresponding natural language summary; for code translation tasks, decoding generates the translated target code; for vulnerability detection tasks, decoding generates a binary discrimination value (1 for the presence of a vulnerability, 0 for the absence of a vulnerability).
[0124] In this embodiment, the evaluation index is calculated as:
[0125] For code summarization tasks, the BLEU (Bilingual Evaluation Understudy) evaluation index is used to measure the generation quality by calculating the n-gram overlap between the generated natural language summary and the reference summary. BLEU-4 is usually used as the evaluation index. BLEU-4 considers the overlap between the generated summary and the reference summary in 1 to 4 consecutive phrases (unigram, bigram, trigram and 4-gram).
[0126] For code translation tasks, the CodeBLEU evaluation index is used. This index combines the structural information of the abstract syntax tree (AST) based on the traditional BLEU index. By comparing the AST structural similarity and n-gram matching between the generated code and the reference code, it can better measure the quality of code translation. CodeBLEU has been proven to be superior to the traditional BLEU index in code translation tasks.
[0127] For vulnerability detection tasks, accuracy, precision, recall and F1 value are used as evaluation indicators.
[0128] Specifically, in this embodiment, the effectiveness of the present invention is evaluated on the CodeXGLUE dataset. The code summarization task is taken as an example to illustrate the indicator evaluation results, see Table 1.
[0129] The results show that the present invention combines the abstract syntax tree with the prefix fine-tuning method to efficiently fine-tune the parameters of the CodeT5-Base model, which can learn and retain the code structure information of the source code and improve the model effect. Compared with the general prefix fine-tuning method, the present invention can effectively improve the effect of code summarization tasks in different languages.
[0130] Table 1 BLUE scores of ordinary prefix fine-tuning and prefix fine-tuning combined with AST on the code summarization task
[0131]
[0132] Corresponding to the above-mentioned embodiment of the method for combining an abstract syntax tree with an efficient parameter fine-tuning code model, the present invention also provides an apparatus for combining an abstract syntax tree with an efficient parameter fine-tuning code model, comprising a memory and one or more processors, wherein the memory stores executable code, and when the processor executes the executable code, it is used to implement the method for combining an abstract syntax tree with an efficient parameter fine-tuning code model in the above-mentioned embodiment.
[0133] The embodiments of the method for efficiently fine-tuning a code model with parameters in combination with an abstract syntax tree can be applied to any device with data processing capabilities, which can be a device or apparatus such as a computer. The device embodiments can be implemented by software, or by hardware or a combination of software and hardware.
[0134] The implementation process of the functions and effects of each unit in the above-mentioned device is specifically described in the implementation process of the corresponding steps in the above-mentioned method, and will not be repeated here.
[0135] For the device embodiment, since it basically corresponds to the method embodiment, the relevant parts can refer to the partial description of the method embodiment. The device embodiment described above is only schematic, in which the units described as separate components may or may not be physically separated, and the components displayed as units may or may not be physical units, that is, they may be located in one place, or they may be distributed on multiple network units. Some or all of the modules can be selected according to actual needs to achieve the purpose of the scheme of the present invention. Ordinary technicians in this field can understand and implement it without paying creative work.
[0136] An embodiment of the present invention further provides a computer-readable storage medium having a program stored thereon. When the program is executed by a processor, the method for efficiently fine-tuning a code model by combining an abstract syntax tree in the above embodiment is implemented.
[0137] The computer-readable storage medium may be an internal storage unit of any device with data processing capability described in any of the aforementioned embodiments, such as a hard disk or a memory. The computer-readable storage medium may also be an external storage device of any device with data processing capability, such as a plug-in hard disk, a smart memory card (Smart Media Card, SMC), an SD card, a flash card (Flash Card), etc. equipped on the device. Furthermore, the computer-readable storage medium may also include both an internal storage unit and an external storage device of any device with data processing capability. The computer-readable storage medium is used to store computer programs and other programs and data required by any device with data processing capability, and may also be used to temporarily store data that has been output or is to be output.
[0138] Those skilled in the art can understand that the above is only a single example of the invention and is not intended to limit the invention. Although the invention is described in detail with reference to the above examples, those skilled in the art can still modify the technical solutions recorded in the above examples or replace some of the technical features therein with equivalents. Any modification, equivalent replacement, etc. made within the spirit and principle of the invention shall be included in the protection scope of the invention.
Claims
1. A method for efficiently fine-tuning a code model using an abstract syntax tree, characterized in that: The method comprises the following steps: S1. Data collection and preprocessing: Collect code snippets as training data and test data; S2. Automatic construction of abstract syntax tree: Automatically analyze code snippets and convert them into abstract syntax tree (AST) containing code structure and syntax information; S3. Convert the abstract syntax tree into a graph structure: Convert the abstract syntax tree into a graph data structure and construct a graph structure containing node and edge relationships; S4. Graph structure embedding: digitize the graph structure through dimensionality reduction embedding technology to generate an abstract syntax tree embedding vector; S5. Graph neural network construction: Using the edge relationships of the graph structure in step S3 and the embedding vectors in step S4 as the input of the graph neural network, the structured representation of the code snippet is learned to obtain the constructed graph neural network; S6. Fine-tuning of code model parameters: Use the constructed graph neural network as an adapter module, and use the training data from step S1 to train the pre-trained code model. Perform efficient parameter fine-tuning during the training process to obtain a fine-tuned code model.
2. The method for efficiently fine-tuning a code model by combining an abstract syntax tree according to claim 1, characterized in that: The step S1 includes: organizing the training data and the test data into different data formats according to different downstream tasks, and cleaning and preprocessing the training data and the test data. The preprocessing includes: S1.1, filter invalid and duplicate code snippets; S1.2, remove redundant information from code snippets; S1.
3. Format the code. The data formats of the different tasks are specifically as follows: (1) Code summary task: <code snippet, corresponding natural language summary>; (2) Code translation task: <source code, target language code>; (3) Vulnerability detection task: <code snippet, whether there is a specific vulnerability>.
3. The method for efficiently fine-tuning a code model by combining an abstract syntax tree according to claim 1, characterized in that: The process of automatically constructing the abstract syntax tree in step S2 includes: S2.
1. Load the syntax file of a specific programming language; S2.
2. Parse the code snippet using the grammar rules defined in the grammar file to generate an abstract syntax tree; S2.
3. Merge and delete redundant branch nodes and leaf nodes in the abstract syntax tree to obtain a simplified abstract syntax tree.
4. The method for efficiently fine-tuning a code model by combining an abstract syntax tree according to claim 1, wherein: In step S3, the method of converting the abstract syntax tree into a graph structure is: S3.
1. Use the root node of the abstract syntax tree as the starting node of the graph structure; S3.2, traverse the abstract syntax tree: S3.2.
1. Map each node in the abstract syntax tree to a node in the graph structure and record the node type information; S3.2.
2. Map the relationship between each node in the abstract syntax tree and its parent node and child nodes into directed edges of the graph structure as edge relationships; S3.
3. Prune the graph structure, remove redundant nodes and directed edges, and generate the final graph structure.
5. The method for efficiently fine-tuning a code model by combining an abstract syntax tree according to claim 1, wherein: The graph structure embedding in step S4 includes: S4.1 performs word segmentation on the types of nodes and source code symbols in the graph structure; S4.2 expands the vocabulary of the pre-trained code model, adds new node types and symbols to the vocabulary, and obtains the word vector matrix of the pre-trained code model; S4.3 Use the word vector matrix of the pre-trained code model to initialize the node embedding vector after word segmentation in the graph structure; S4.4 combines the node embedding vectors after word segmentation of each node into a node embedding vector by averaging or weighted summation.
6. The method for efficiently fine-tuning a code model by combining an abstract syntax tree according to claim 1, characterized in that: The efficient parameter fine-tuning method in step S6 is: S6.
1. Load the pre-trained code model; S6.
2. Use the graph neural network constructed in step S5 as an adapter module and connect it to the pre-trained code model through soft prompting or prefix fine-tuning. S6.
3. On the training data of the downstream task, only fine-tune the adapter module parameters in the code model and freeze the rest of the code model.
7. The method according to claim 6, characterized in that In step S6.2, the soft hint fine-tuning method is as follows: the vector output of the graph neural network is inserted into the input end of the pre-trained code model as a "soft hint", and the "soft hint" is spliced with the text embedding vector of the source code fragment as the input of the encoder in the code model; in the fine-tuning stage, only the parameters of the graph neural network vector are updated, and the rest of the code model is frozen.
8. The method according to claim 6, characterized in that In step S6.2, the prefix fine-tuning method is as follows: a learnable prefix vector is introduced in each multi-head attention layer (Multi-Head Attention Layer) of the encoder and decoder of the code model. The introduction method is: the output of the graph embedding module is used as the prefix vector and spliced with the key-value matrix of the multi-head attention layer.
9. Application of a code model obtained by the method according to any one of claims 1 to 8 in a code task.
10. The use according to claim 9, characterized in that The code tasks are: Code summarization task: Input code snippets into the model and decode them to generate corresponding natural language descriptions; Vulnerability detection task: Input code snippets into the model, decode and generate vulnerability types or vulnerability probability; Code translation task: input source code into the model and decode it to generate code in the target language.
Citation Information
Patent Citations
C source code vulnerability detection method based on Bert model and BiLSTM
CN113420296A
Text information extraction method based on large language model and efficient parameter fine tuning
CN118132674A
Code representation generation method and device, storage medium and electronic equipment
CN116661805A
Three-dimensional pre-training large model parameter efficient fine tuning method and system
CN117252986A
Code detection method and related equipment
CN117667183A
Cited By
Low-code platform operation method and system, electronic equipment and storage medium
CN118963746A
Vulnerability detection method based on code change large model
CN119646819A
Method and device for finely adjusting code model
CN119988198A
Code generation model training method, device and equipment
CN120873595A
Code generation model training methods, devices and equipment
CN120873595B
