A vulnerability repair model construction method based on abstract syntax tree position coding
By using an abstract syntax tree-based positional encoding method, Clang segmentation positions are mapped to BPE segmentation positions, and RoPE is extended, which solves the shortcomings of the Transformer model in positional recognition and improves the performance of the vulnerability remediation model.
Patent Information
- Application Number
- CN202510783424.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-12
- Publication Date
- 2026-11-20
- Estimated Expiration
- 2045-06-12
AI Technical Summary
Existing vulnerability remediation models, when utilizing Transformers, lack the ability to identify the position of tokens in the code sequence. This causes the attention mechanism to be unable to effectively distinguish the relative or absolute position of tokens, affecting the model's understanding of code structure and the effectiveness of vulnerability remediation.
We employ an abstract syntax tree-based positional encoding method to map the positional sequence of Clang segmentation to the positional sequence of BPE segmentation, and extend the rotational positional encoding (RoPE) to construct a 2D positional fusion module. This enhances the positional awareness of the Transformer and provides a positional identifier for each token in the sequence through positional encoding.
It improves the Transformer model's ability to understand code structure, reduces irrelevant attention computation, and enhances the repair performance of the vulnerability repair model.
Smart Images

Figure CN120688058B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to a program vulnerability repair technology, specifically a vulnerability repair model construction method based on abstract syntax tree position encoding, belonging to the field of software security. Background Technology
[0002] While research in the field of automated vulnerability remediation is not abundant, it is still frequently seen in academic research. From traditional dynamic and static analysis methods to deep learning-based approaches, researchers are constantly innovating to safeguard software security. Consequently, with the rapid increase in software vulnerabilities, vulnerability remediation technologies are also evolving rapidly. Vulnerability remediation is often intertwined with program errors, and sometimes they can even be converted into each other. In some cases, there is a clear boundary between the two, while in others, the distinction is blurred. Faced with this situation, some researchers have combined the remediation of both, especially after the development of deep learning. This is because program error remediation data is easier to obtain than high-quality vulnerability remediation data, and a large amount of program error data is crucial for training deep learning models. Based on the idea of transfer learning, the knowledge of the model trained in the source domain can be used in the target domain. Chen et al. compiled vulnerability remediation data and program error datasets based on transfer learning and trained the Transformer model VRepair. This method has become the foundation for many subsequent automated vulnerability remediation methods, including this study, which utilize transfer learning when training their respective remediation models and incorporate VRepair into baseline comparison methods.
[0003] Previous research methods have often incorporated textual sequences of code structures, such as ASTs or DFGs, or vector representations processed by intermediate models, into repair models. Even after the advent of Transformers, research on adding code structures continued in this manner, enabling models to perceive the code structure. However, one of the most significant advantages of Transformers compared to previous CNNs and RNNs is their attention mechanism. While attention mechanisms allow different tokens in a sequence to pay attention to each other, it's important to note that this mechanism, relying on the inner product of vectors, lacks the ability to recognize the order of tokens; it is order-insensitive. This means that without additional information, the attention mechanism cannot distinguish the relative or absolute positions of tokens in the sequence. Therefore, to compensate for this deficiency and enable the model to perceive positional information in the sequence, positional encoding is needed. Positional encoding provides a positional identifier for each token in the sequence, allowing the attention mechanism to indirectly perceive their positional relationships even if it doesn't directly consider their order when processing them. Summary of the Invention
[0004] The purpose of this invention is to provide a vulnerability repair model construction method based on Abstract Syntax Tree (AST) positional encoding, which extends the one-dimensional Transformer sequence position to a 2D position. The AST sequence position is replaced by the parent node position after the simplified AST is processed by the parent representation. To address the mismatch between the positional representations after code is segmented by the Clang and BPE tokenizers, a mapping algorithm is designed, and a positional fusion module for the encoder and decoder is implemented through Extended Rotational Position Encoding (RoPE).
[0005] The technical solution adopted in this invention is as follows: A method for constructing a vulnerability remediation model based on abstract syntax tree positional encoding:
[0006] Step 1: Obtain the 2D position sequence based on the abstract syntax tree;
[0007] 1.1: Prepare a source code snippet containing the vulnerability;
[0008] 1.2: The source code, after lexical analysis, will be parsed into a series of tokens, denoted as C. code ={c1, c2, ..., c n}, C code This represents a sequence of tokens in Clang, where each token has its own absolute position, denoted as P. original = {1, 2, ..., n}, where n is the length of the Clang segmented sequence;
[0009] 1.3: Generate an AST based on lexical analysis. At this time, the nodes of the AST contain two kinds of information: node type and position information.
[0010] 1.4: Replace the token represented by each node in the AST with the absolute position P of that token in the source code text sequence. original After the above steps, the AST is simplified into a simplified abstract syntax tree (SAST) where all nodes are represented only by numbers. Then, the parent representation is used to represent this simplified abstract syntax tree, forming a 2D positional sequence C(P) under Clang tokenization. original P ast ), C represents Clang segmentation, P original P represents the original position information of each node in the Clang word segmentation sequence. ast This represents the original position information of the parent node of each node in the Clang word segmentation sequence.
[0011] 1.5 To address the word overflow problem, a BPE segmenter is used based on the transformer, thus requiring the implementation of a transformation from the Clang position to the BPE position. The requirements for using BPE segmentation are: scan the code sequence from left to right, selecting the longest matching sub-word unit for segmentation each time; for the i-th token c under Clang segmentation... i After processing by the BPE tokenizer, it will be split into multiple smaller tokens. j+1 b j+2 ...}, originally the entire sequence C represented by Clang tokenization. code ={c1, c2, ..., c n}, represented as B in BPE word segmentation. code ={b1, b2, ..., b m}; for locators that pinpoint vulnerable areas <SAST_StartBug>、<SAST_EndBug> and patch locator<SAST_ModStart> ,<SAST ModEnd> And the whitespace character in the code's text suggestions.<SAST blank> All are set to the complete token under BPE segmentation, and are no longer further decomposed into sub-words; a special token "CWE-XXX" is added before the vulnerable code to indicate which CWE category the vulnerability belongs to. For unknown vulnerabilities, "CWE-000" is used to indicate "general fix"; "CWE-XXX" is set to the complete token under BPE segmentation.
[0012] 1.6 Hooks the sequence positions of Clang and BPE segmentation with the positions of the original code string, thereby achieving the result of C(P) segmentation. original P ast ) to B(P original P ast The mapping of B(P); the specific algorithm is implemented by the proposed algorithm 1, B(P) original P ast P in ) original For sequential position, P ast The results of Algorithm 1 show that its inputs are source code and a Clang word segmentation sequence C. code BPE word segmentation B code ;
[0013] Algorithm 1 is as follows: mapClangToBPE first calculates the c in the source code. i The start and end indices (where i = 1, ..., n) are represented by Formula 1; then, b is calculated. j(where j = 1, ..., m) are the start and end indices in the source code, represented by Formula 2; then hasmapBtoC is initialized, where the key corresponds to P obtained through BPE tokenization. original The value corresponds to P obtained through Clang. original HasmapCtoB acts as the inverse mapping: its keys correspond to Clang positions, and its values correspond to BPE positions; if a string is split into multiple sub-words by BPE, then the starting index of the string must be less than or equal to the starting index of all its sub-words, and the ending index must be greater than or equal to the ending index of all its sub-words; by comparing O Clang and O BPE Establish two word segmentation methods for P original The correspondence between them is shown in Formula 3. When a string is split into multiple subwords, only the position of the first subword is recorded in hasmapCtoB. Finally, the algorithm returns two hashmaps. Using these two hashmaps, the final B(P) can be obtained. original P ast ), B(P original P ast This is the final 2D position sequence;
[0014] O Clang (C, T) Clang )={(s c1 ,e c1 ), s c2 e c2 ), ..., (s cn e cn )) (1)
[0015] O BPE (C, T) BPE )={(s B1 e B1 ), (s B2 e B2 ), …, s Bm ,e Bm (2)
[0016]
[0017] Step 2: Extend Rotary Position Embedding (RoPE) to adapt to 2D position sequences, thereby constructing a position fusion module;
[0018] Location information is added to Q and K of the attention mechanism. Different location fusion modules are proposed for the encoder and decoder because their methods of processing word vectors are slightly different. The encoder processes sequences of fixed length, and the input code is complete. After being parsed by the Clang analyzer, a complete AST tree is obtained, which then forms the 2D location encoding B(P) under BPE segmentation. original P ast ), using B(P original P ast The location fusion module is denoted as the Original-AST(OA) module; the decoder's location fusion module is designed to use 2D location encoding, but both dimensions are in the form of absolute position B(P). original P original ), using B(P original P original The location fusion module is denoted as the Original-Original(OO) module.
[0019] 2.1 OA Location Fusion Module
[0020] In the encoder fusion OA module, assuming vectors q and k come from Q and K respectively, with vector dimension d, their corresponding 2D positions in Q and K are (m... o m A ) and (n o n A Then, by extending RoPE to the form of a block matrix, the location information (m) can be made available. o m A ) and (n o n A The vectors are integrated into vectors q and k, as shown in formulas 4 and 5:
[0021]
[0022] Where q f Represents the first d / 2 dimensions (q0, q1, ..., q d / 2-2 q d / 2-1 ) T q l Represents the last d / 2 dimensions (q) d / 2 q d / 2+1 , ..., q d-2 q d-1 ) T Rotation matrix and As shown in formulas 6 and 7 respectively, and Similarly, we can obtain that θ = 10000 -2i / d ;
[0023]
[0024] As shown in formulas 8, 9, and 10, the calculation of attention scores using q and k dynamically incorporates n. o -m o Such relative positional information;
[0025]
[0026] According to RoPE's original formula 3-10, R n-m Orthogonal matrix
[0027]
[0028] It can be seen that in 3-11 It is an orthogonal matrix, and therefore Orthogonal matrix
[0029]
[0030] use as well as To address the sparsity of Equation 5, a more computationally efficient implementation method is proposed, as shown in Equation 11.
[0031] After fusing the above location information, the initial query Q and key K contain absolute location information. The original location is incorporated into the first d / 2 dimensions, and the AST sequence information is incorporated into the last d / 2 dimensions. In the subsequent self-attention calculation process, the result carries relative location information through inner product operations.
[0032]
[0033] Using the same method, a more computationally efficient implementation method than directly applying Formula 4 will be derived, as shown in Formula 12;
[0034] For calculations of other parts of the encoder, the formula is as follows:
[0035]
[0036] Formula 12 represents the output of the previous encoder. Output of multi-head self-attention after layer normalization (LN) Formula 13 indicates After passing through the FeedForward neural network, residual connections and layer normalization are performed again.
[0037] 2.2 OA Location Fusion Module
[0038] The cross-attention mechanism in the decoder allows one sequence to focus on relevant parts of another sequence during generation. Its query Q comes from the self-attention in the decoder, while the key K and value V come from the last layer output of the encoder. Following the approach in the encoder, the OA position fusion module is applied to the K and V of the cross-attention in the decoder. For the self-attention mechanism of the decoder, a 2D positional encoding B(P) with both dimensions being the original position is used. original ,P original The length automatically increases as the input sequence increases, and the process of position fusion using RoPE is the same as the method in 2.1;
[0039] For the calculations of other parts of the decoder, the formulas are as follows:
[0040]
[0041] Equation 14 represents the self-attention of the current decoder. With the encoder's final output In cross-attention calculation, Equation 15 represents the output of the previous decoder. Output of multi-head self-attention after layer normalization (LN) Formula 16 represents After passing through the FeedForward neural network, residual connections and layer normalization are performed again.
[0042] The model uses linear layers to process the final output of the decoder. Transform it into a vector z, whose dimension is equal to the size V of the vocabulary, i.e., z∈R. V Each element z i Let z represent the unnormalized score logits of the i-th token in the vocabulary. Finally, the Softmax function transforms the vector z into a probability distribution for each token.
[0043]
[0044] in, It is the exponential function value of the i-th logits. It is the sum of the exponential function values of all logits, used for normalization;
[0045] The input to the vulnerability remediation model is code sequence B. code And a vulnerability type token added at the beginning, wherein the 2D position encoding schemes in the position fusion modules of the encoder and decoder are respectively (P original ,P ast ) and (P original ,P original The vulnerability remediation model generates a patch Rep = {r1, r2, ..., r}.n}, r i This represents the token in the patch. The task of model training is to learn the vulnerability patch pair {B} by minimizing the cross-entropy loss function. code The features of ,Rep} are used to generate patch predictions, as shown in Equation 3-18:
[0046]
[0047] Rep is a reference repair. t Rep represents the token generated at time t. <t B represents the repair token generated before time t. code This represents the token sequence under BPE segmentation.
[0048] Step 3: Insert the location fusion module into the transformer-based model to form the final vulnerability remediation model;
[0049] 3.1: Encoder position fusion module: Inserted into encoder self-attention and decoder cross-attention; Insert the OA position fusion module into any transformer-based model. The OA position fusion module is inserted after encoder self-attention Q, K, and decoder cross-attention K, V.
[0050] 3.2: Decoder position fusion module: Inserted into the decoder self-attention. Insert the OO position fusion module into any transformer-based model. After the OO position fusion module is inserted into the decoder self-attention Q and K, and after the OA and OO position modules are inserted, the vulnerability repair model is completed and then trained using conventional training methods.
[0051] The beneficial effects of this invention are as follows: By deeply analyzing the attention mechanism in the Transformer architecture, which captures the absolute and relative positional relationships between tokens through positional encoding, this research is inspired to use positional sequences to annotate the structural hierarchy of the input code sequence. In terms of code structure analysis, this invention employs an Abstract Syntax Tree (AST) and simplifies it appropriately for digital positional representation. To address the word overflow (OOV) problem, this invention designs an algorithm that maps positional sequences based on Clang segmentation to positional sequences based on byte-pair encoding (BPE), forming a 2D positional encoding. Furthermore, to effectively integrate the 2D positional encodings of the encoder and decoder into the model, this research extends the Rotated Positional Encoding (RoPE) to a block matrix form, constructing an OA positional module for the encoder and an OO positional module for the decoder. This enhances the model's understanding of the code structure without increasing the length of the additional input sequence and reduces irrelevant attention computations. Attached Figure Description
[0052] Figure 1 To simplify the abstract syntax tree process diagram;
[0053] Figure 2 Example diagram of 2D position encoding;
[0054] Figure 3 Here is a flowchart of the mapClangToBPE algorithm;
[0055] Figure 4 Example diagram of the insertion position fusion module;
[0056] Figure 5 A diagram illustrating the overall framework of the model construction method. Detailed Implementation
[0057] Step 1: Obtain the 2D position sequence based on the abstract syntax tree, such as Figure 1 As shown:
[0058] 1.1: Prepare a source code snippet containing the vulnerability;
[0059] 1.2: The source code, after lexical analysis, will be parsed into a series of tokens, denoted as C. code ={c1, c2, ..., c n}, C code This represents a sequence of tokens in Clang, where each token has its own absolute position, denoted as P. original = {1, 2, ..., n}, where n is the length of the Clang segmented sequence;
[0060] 1.3: Based on lexical analysis, an AST is further generated. At this time, the nodes of the AST usually contain two types of information: node type (such as declaration, identifier, function name, etc.) and position information (line number and column number in the source code, etc.).
[0061] 1.4: Replace the token represented by each node in the AST with the absolute position P of that token in the source code text sequence. original After the above steps, the AST is simplified into a Simplified Abstract Syntax Tree (SAST) where all nodes are represented only by numbers. Then, the parent representation is used to represent this simplified SAST, forming a 2D positional sequence C(P) under Clang tokenization. original P ast ), C represents Clang segmentation, P original P represents the original position information of each node in the Clang word segmentation sequence. astThis represents the original position information of the parent node of each node in the Clang word segmentation sequence.
[0062] 1.5 To address the word overflow problem, a BPE segmenter is used based on the transformer, thus requiring the implementation of a transformation from the Clang position to the BPE position. The requirements for using BPE segmentation are: scan the code sequence from left to right, selecting the longest matching sub-word unit for segmentation each time; for the i-th token c under Clang segmentation... i After processing by the BPE tokenizer, it will be split into multiple smaller tokens. j+1 b j+2 ...}, originally the entire sequence C represented by Clang tokenization. code ={c1, c2, ..., c n}, represented as B in BPE word segmentation. code ={b1, b2, ..., b m}; for locators that pinpoint vulnerable areas <SAST_StartBug>、<SAST_EndBug> and patch locator<SAST_ModStart> ,<SAST ModEnd> And the whitespace character in the code's text suggestions.<SAST blank> All are set to the complete token under BPE segmentation, and are no longer further decomposed into sub-words; a special token "CWE-XXX" is added before the vulnerable code to indicate which CWE category the vulnerability belongs to. For unknown vulnerabilities, "CWE-000" is used to indicate "general fix"; "CWE-XXX" is set to the complete token under BPE segmentation.
[0063] 1.6 Hooks the sequence positions of Clang and BPE segmentation with the positions of the original code string, thereby achieving the result of C(P) segmentation. original P ast ) to B(P original P ast The mapping of B(P); the specific algorithm is implemented by the proposed algorithm 1, B(P) original P ast P in ) original For sequential position, P ast The results of Algorithm 1 show that its inputs are source code and a Clang word segmentation sequence C. code BPE segmentation B code ;
[0064] Algorithm 1 is as follows: mapClangToBPE first calculates the start and end indices of ci (where i = 1, ..., n) in the source code, represented by Formula 1; then, it calculates b... j(where j = 1, ..., m) are the start and end indices in the source code, represented by Formula 2; then hasmapBtoC is initialized, where the key corresponds to P obtained through BPE tokenization. original The value corresponds to P obtained through Clang. original HasmapCtoB acts as the inverse mapping: its keys correspond to Clang positions, and its values correspond to BPE positions; if a string is split into multiple sub-words by BPE, then the starting index of the string must be less than or equal to the starting index of all its sub-words, and the ending index must be greater than or equal to the ending index of all its sub-words; by comparing O Clang and O BPE Establish two word segmentation methods for P original The correspondence between them is shown in Formula 3. When a string is split into multiple subwords, only the position of the first subword is recorded in hasmapCtoB. Finally, the algorithm returns two hashmaps. Using these two hashmaps, the final B(P) can be obtained. original P ast ), B(P original P ast This is the final 2D position sequence;
[0065] O Clang (C, T) Clang )={(s c1 ,e c1 ), s c2 e c2 ), ..., (s cn e cn )) (1)
[0066] O BPE (C, T) BPE )={(s B1 e B1 ), (s B2 e B2 ), ..., s Bm ,e Bm (2)
[0067]
[0068] Step 2: Extend Rotary Position Embedding (RoPE) to adapt to 2D position sequences, thereby constructing a position fusion module;
[0069] Location information is added to Q and K of the attention mechanism. Different location fusion modules are proposed for the encoder and decoder because their methods of processing word vectors are slightly different. The encoder processes sequences of fixed length, and the input code is complete. After being parsed by the Clang analyzer, a complete AST tree is obtained, which then forms the 2D location encoding B(P) under BPE segmentation. original P ast ), using B(P original P ast The location fusion module is denoted as the Original-AST(OA) module; the decoder's location fusion module is designed to use 2D location encoding, but both dimensions are in the form of absolute position B(P). original P original ), using B(P original P original The location fusion module is denoted as the Original-Original(OO) module.
[0070] 2.1 OA Location Fusion Module
[0071] In the encoder fusion OA module, assuming vectors q and k come from Q and K respectively, with vector dimension d, their corresponding 2D positions in Q and K are (m... o m A ) and (n o n A Then, by extending RoPE to the form of a block matrix, the location information (m) can be made available. o ,m A ) and (n o ,n A The vectors are integrated into vectors q and k, as shown in formulas 4 and 5:
[0072]
[0073] Where q f Represents the first d / 2 dimensions (q0, q1, ..., q d / 2-2 ,q d / 2-1 ) T q l Represents the last d / 2 dimensions (q) d / 2 ,q d / 2+1 ,…,q d-2 ,q d-1 ) T Rotation matrix and As shown in formulas 6 and 7 respectively, and Similarly, we can obtain that θ = 10000 -2i / d ;
[0074]
[0075] As shown in formulas 8, 9, and 10, the calculation of attention scores using q and k dynamically incorporates n. o -m o Such relative positional information;
[0076]
[0077] According to RoPE's original formula 3-10, R n-m Orthogonal matrix
[0078]
[0079] It can be seen that in 3-11 It is an orthogonal matrix, and therefore Orthogonal matrix
[0080]
[0081] use as well as To address the sparsity of Equation 5, a more computationally efficient implementation method is proposed, as shown in Equation 11.
[0082] After fusing the above location information, the initial query Q and key K contain absolute location information. The original location is incorporated into the first d / 2 dimensions, and the AST sequence information is incorporated into the last d / 2 dimensions. In the subsequent self-attention calculation process, the result carries relative location information through inner product operations.
[0083]
[0084] Using the same method, a more computationally efficient implementation method than directly applying Formula 4 will be derived, as shown in Formula 12;
[0085] For calculations of other parts of the encoder, the formula is as follows:
[0086]
[0087] Formula 12 represents the output of the previous encoder. Output of multi-head self-attention after layer normalization (LN) Formula 13 indicates After passing through the FeedForward neural network, residual connections and layer normalization are performed again.
[0088] 2.2 OA Location Fusion Module
[0089] The cross-attention mechanism in the decoder allows one sequence to focus on relevant parts of another sequence during generation. Its query Q comes from the self-attention in the decoder, while the key K and value V come from the last layer output of the encoder. Following the approach in the encoder, the OA position fusion module is applied to the K and V of the cross-attention in the decoder. For the self-attention mechanism of the decoder, a 2D positional encoding B(P) with both dimensions being the original position is used. original ,P original The length automatically increases as the input sequence increases, and the process of position fusion using RoPE is the same as the method in 2.1;
[0090] For the calculations of other parts of the decoder, the formulas are as follows:
[0091]
[0092] Equation 14 represents the self-attention of the current decoder. With the encoder's final output In cross-attention calculation, Equation 15 represents the output of the previous decoder. Output of multi-head self-attention after layer normalization (LN) Formula 16 represents After passing through the FeedForward neural network, residual connections and layer normalization are performed again.
[0093] The model uses linear layers to process the final output of the decoder. Transform it into a vector z, whose dimension is equal to the size V of the vocabulary, i.e., z∈R. V Each element z i Let z represent the unnormalized score logits of the i-th token in the vocabulary. Finally, the Softmax function transforms the vector z into a probability distribution for each token.
[0094]
[0095] Among them, e zi It is the exponential function value of the i-th logits. It is the sum of the exponential function values of all logits, used for normalization;
[0096] The input to the vulnerability remediation model is code sequence B. code And a vulnerability type token added at the beginning, wherein the 2D position encoding schemes in the position fusion modules of the encoder and decoder are respectively (P original ,P ast ) and (P original ,P original The vulnerability remediation model generates a patch Rep = {r1, r2, ..., r}.n}, r i This represents the token in the patch. The task of model training is to learn the vulnerability patch pair {B} by minimizing the cross-entropy loss function. code The features of ,Rep} are used to generate patch predictions, as shown in Equation 3-18:
[0097]
[0098] Among them, Rep is the reference repair. t Rep represents the token generated at time t. <t B represents the repair token generated before time t. code This represents the token sequence under BPE segmentation.
[0099] Step 3: Insert the location fusion module into the transformer-based model to form the final vulnerability remediation model;
[0100] 3.1: Encoder position fusion module: Inserted into encoder self-attention and decoder cross-attention; Insert the OA position fusion module into any transformer-based model. The OA position fusion module is inserted after encoder self-attention Q, K, and decoder cross-attention K, V.
[0101] 3.2: Decoder position fusion module: Inserted into the decoder self-attention. Insert the OO position fusion module into any transformer-based model. After the OO position fusion module is inserted into the decoder self-attention Q and K, and after the OA and OO position modules are inserted, the vulnerability repair model is completed and then trained using conventional training methods.
[0102] Example 1:
[0103] To measure the remediation performance of the remediation model, a location fusion module was inserted into the pre-trained base model CodeT5 to form the final vulnerability remediation model. Six remediation models, including this invention, were trained on the same vulnerability dataset. Two evaluation metrics were used: Perfect Predictions (%PP) and CodeBLEU (higher scores indicate better performance in both metrics). The model was also compared with five other automatic vulnerability remediation models: VQM, VulMaster, VulRepair, VRepair, and GraphCodeBERT. Detailed descriptions are as follows:
[0104] 1) VQM: Vulnerable areas are labeled by learning a model VM that shows the relationship between vulnerable tokens and repair tokens. The CodeT5 model is used as the vulnerability repair model, and the attention output of the CodeT5 model is weighted by the VM so that VQ queries can focus on vulnerable areas.
[0105] 2) VulMaster: Input the code, AST, vulnerability type and fix case into the Fusion-in-Decoder (FiD) framework to obtain their respective feature representations, and then merge these intermediate results into the decoder.
[0106] 3) VRepair: Uses a traditional vanilla Transformer architecture for automated vulnerability remediation tasks.
[0107] 4) VulRepair: A CodeT5-based method that learns vulnerability fixes directly from a fix corpus.
[0108] 5) GraphCodeBERT: An extended version of CodeBERT that takes into account the data flow graph during training and adapts to vulnerability remediation tasks by continuing to train on vulnerability remediation datasets.
[0109] The comparison results are shown in Table 1. Compared with other vulnerability repair models, the method used in this invention achieves the best performance in both metrics when the beam search is 1, 3, and 5.
[0110] Table 1. Performance Comparison of Various Repair Methods
[0111]
Claims
1. A method for constructing a vulnerability remediation model based on abstract syntax tree positional encoding, characterized in that: Step 1: Obtain the 2D position sequence based on the abstract syntax tree; The specific method is as follows: Step 1.1: Prepare a source code snippet containing the vulnerability; Step 1.2: The source code, after lexical analysis, will be parsed into a series of tokens, denoted as... , This represents a sequence of tokens in Clang, where each token has its own absolute position in the order, denoted as... , The length of the Clang segmented sequence; Step 1.3: Generate an AST based on lexical analysis. At this point, the nodes in the AST contain two types of information: node type and position information. Step 1.4: Replace the token represented by each node in the AST with the absolute position of that token in the source code text sequence. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l After the above steps, the AST is simplified into a simplified abstract syntax tree (SAST) where all nodes are represented only by numbers. Then, the parent representation is used to represent this simplified abstract syntax tree, forming a 2D positional sequence C(t) under Clang tokenization. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ), C represents Clang segmentation, 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l This represents the original position information of each node in the Clang word segmentation sequence, 𝑃 𝑎𝑠𝑡 This represents the original position information of the parent node of each node in the Clang word segmentation sequence; Step 1.5: To solve the vocabulary overflow problem, the BPE segmenter is used based on the transformer. Therefore, it is necessary to implement the transformation from the Clang position to the BPE position. The requirements for using BPE segmentation are: scan the code sequence from left to right, and select the longest matching sub-word unit for segmentation each time; for the i-th token under Clang segmentation... After being processed by the BPE tokenizer, it will be split into multiple smaller tokens. The entire sequence originally represented by Clang tokenization In BPE segmentation, it is represented as ; for locators that pinpoint vulnerable areas<SAST_StartBug> ,<SAST_EndBug> and patch locator<SAST_ModStart> <SAST_ModEnd> and the whitespace character in the code hints.<SAST_blank> All are set to the complete token under BPE segmentation, and are no longer further decomposed into sub-words; a special token "CWE-XXX" is added before the vulnerable code to indicate which CWE category the vulnerability belongs to. For unknown vulnerabilities, "CWE-000" is used to indicate "general fix"; "CWE-XXX" is set to the complete token under BPE segmentation. Step 1.6: Hook the sequence positions of Clang and BPE segmentation with the positions of the original code string, thereby achieving the result of C(𝑃) segmentation. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ) to B (𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 Mapping of ) The specific algorithm is implemented by the proposed Algorithm 1, B(𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ) 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l For sequential position, 𝑃 𝑎𝑠𝑡 The results of Algorithm 1 show that its inputs are source code and Clang word segmentation sequences. BPE word segmentation ; Algorithm 1 is as follows: First, calculate the value of in the source code. 𝑖 The start and end indices of (where 𝑖 = 1, …, 𝑛) are represented by Formula 1; next, 𝑏 is calculated. 𝑗 (where 𝑗 = 1, …, 𝑚) are the start and end indices in the source code, represented by Formula 2; then h𝑎𝑠𝑚𝑎𝑝𝐵𝑡𝑜𝐶 is initialized, where the key corresponds to 𝑃 obtained through BPE tokenization. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l The value corresponds to the 𝑃 obtained through Clang. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l ;hsssss> is used as the inverse mapping: its keys correspond to Clang positions, and its values correspond to BPE positions; if a string is split into multiple sub-words by BPE, then the starting index of the string must be less than or equal to the starting index of all its sub-words, and the ending index must be greater than or equal to the ending index of all its sub-words; by comparing 𝑂 𝐶l𝑎𝑛𝑔 and 𝑂 𝐵𝑃𝐸 Establish two word segmentation methods under 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l The correspondence between them is shown in Formula 3; when a string is split into multiple subwords, only the position of the first subword is recorded in hShashMap. Finally, the algorithm returns two hShashMaps; using these two hashmaps, the final B(B) can be obtained. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ), B (𝑃) 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 This is the final 2D position sequence; Step 2: Extend the rotational position encoding to adapt to the 2D position sequence, thereby constructing a position fusion module; Step 3: Insert the location fusion module into the transformer-based model to form the final vulnerability remediation model; Step 3.1: Encoder position fusion module: Inserted into the encoder self-attention and decoder cross-attention; Step 3.2: Decoder position fusion module: Inserted into the decoder self-attention.
2. The vulnerability remediation model construction method based on abstract syntax tree positional encoding according to claim 1, characterized in that: The specific method in step 2 is as follows: Location information is added to Q and K of the attention mechanism. Different location fusion modules are proposed for the encoder and decoder because their methods of processing word vectors are slightly different. The encoder processes sequences of fixed length, and the input code is complete. After being parsed by the Clang analyzer, a complete AST tree is obtained, which then forms the 2D location encoding B(t) under BPE segmentation. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ), using B (𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 The location fusion module is denoted as Original-AST, which is the OA module; the decoder's location fusion module is designed to use 2D location encoding, but both dimensions are in the form of absolute position B(t). 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l ), using B (𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l The location fusion module is denoted as Original-Original, which is the OO module; Step 2.1: OA Location Fusion Module In the encoder fusion OA module, assuming vectors 𝑞 and 𝑘 come from Q and K respectively, with vector dimension d, their corresponding 2D positions in Q and K are (𝑚) and (𝑘). 𝑜 , 𝑚 A ) and (𝑛 𝑜 , 𝑛 A Then, by extending RoPE to the form of a block matrix, the location information (𝑚) can be made available. 𝑜 , 𝑚 A ) and (𝑛 𝑜 , 𝑛 A The vectors 𝑞 and 𝑘 are merged into each other, as shown in formulas 4 and 5: in Represents the first d / 2 dimensions , Represents the last d / 2 dimensions Rotation matrix and As shown in formulas 6 and 7 respectively, where ; As shown in formulas 8, 9, and 10, the process of calculating attention scores for and dynamically incorporates... Such relative positional information; According to RoPE's original formula 3-10, Orthogonal matrix It can be seen that in 3-11 , It is an orthogonal matrix, and therefore Orthogonal matrix After fusing the above location information, the initial query Q and key K contain absolute location information. The original location is incorporated into the first d / 2 dimensions, and the AST sequence information is incorporated into the last d / 2 dimensions. In the subsequent self-attention calculation process, the result carries relative location information through inner product operations. For calculations of other parts of the encoder, the formula is as follows: Formula 12 represents the output of the previous encoder. Output of multi-head self-attention after layer normalization (LN) Formula 13 indicates After feedforward neural network Then residual connections and layer normalization are performed again; Step 2.2: OA Location Fusion Module The cross-attention mechanism in the decoder allows one sequence to focus on relevant parts of another sequence during generation. Its query Q comes from the self-attention in the decoder, while the key K and value V come from the last layer output of the encoder. Following the approach in the encoder, the OA position fusion module is applied to the K and V of the cross-attention in the decoder. For the decoder's self-attention mechanism, a 2D positional encoding B(k) with both dimensions being the original position is used. 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l The length automatically increases as the input sequence increases, and the process of position fusion using RoPE is the same as the method in 2.1; For the calculations of other parts of the decoder, the formulas are as follows: Equation 14 represents the self-attention of the current decoder. With the encoder's final output In cross-attention calculation, Equation 15 represents the output of the previous decoder. Output of multi-head self-attention after layer normalization (LN) Formula 16 indicates After feedforward neural network Then residual connections and layer normalization are performed again; The model uses linear layers to process the final output of the decoder. Convert to a vector Its dimension is equal to the size V of the vocabulary, that is Each element This represents the unnormalized score logits of the i-th token in the vocabulary. Finally, the Softmax function converts the vector... Probability distribution for each token: in, It is the exponential function value of the i-th logits. It is the sum of the exponential function values of all logits, used for normalization; The input to the vulnerability remediation model is a code sequence. And a vulnerability type token added at the beginning, wherein the 2D position encoding schemes in the position fusion modules of the encoder and decoder are respectively (𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑎𝑠𝑡 ) and (𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l , 𝑃 𝑜𝑟𝑖𝑔𝑖𝑛𝑎l Vulnerability remediation model generates patch fixes. , This represents the token in the patch. The task of model training is to learn the vulnerability patch pair by minimizing the cross-entropy loss function. The features are used to generate patch predictions, as shown in Equation 3-18: in, This is a reference repair. This represents the token generated at time t. This represents the repair token generated before time t. This represents the token sequence under BPE segmentation.
3. The vulnerability remediation model construction method based on abstract syntax tree positional encoding according to claim 1, characterized in that: The specific method in step 3 is as follows: Step 3.1: Insert the OA location fusion module into any transformer-based model The OA position fusion module is inserted after the encoder's self-attention Q, K, and after the decoder's cross-attention K, V; Step 3.2: Insert the OO position fusion module into any transformer-based model After the OO location fusion module is inserted into the decoder after the self-attention Q and K, and after the OA and OO location modules are inserted, the vulnerability remediation model is completed and then trained using conventional training methods.
