A method, system and device for automatic code completion based on deep reinforcement learning
By combining deep reinforcement learning and code type information in code completion, a hybrid reward mechanism is constructed, which solves the problem of code type information not being effectively used in the existing technology, improves the accuracy and efficiency of the code completion process, and improves Improve software development and maintenance efficiency.
Patent Information
- Application Number
- CN202410970779.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-19
- Publication Date
- 2024-09-17
- Estimated Expiration
- 2044-07-19
AI Technical Summary
Existing code completion methods fail to effectively utilize code type information, resulting in generated code that is inconsistent or inaccurate in type, increasing developers' time and work pressure in processing complex logic.
Using a method based on deep reinforcement learning, code type information is combined with reinforcement learning to build a hybrid reward mechanism with immediate rewards and delayed rewards. Through multi-task learning and deep reinforcement learning, the policy network and evaluation network are trained to guide the code completion process and ensure Accuracy of generated code snippets.
It improves the accuracy and efficiency of code completion, saves developers time in processing complex logic, and improves the efficiency of software development and maintenance.
Smart Images

Figure CN118519681B
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of software development and maintenance automation, and specifically, relates to a method, system and device for automatic code completion based on deep reinforcement learning. Background Art
[0002] With the rapid development of Internet technology, software has become increasingly large and its architecture has become increasingly complex. These software cover all aspects of people's lives and play an increasingly important role. With the continuous iteration and update of application software, developers need to deal with more code and more complex logic, which brings increasing work pressure to program developers. In this context, code completion technology has become a key function in modern integrated development environments. It can automatically complete the completion of subsequent code elements according to the program context, effectively helping developers improve programming efficiency, reduce typing errors and speed up coding, and plays a vital role in the fast-paced development process. However, the current methods do not effectively use code type information to guide the model in the intermediate process of code completion. Therefore, in the process of code completion, the model is not constrained by type information, which may cause the generated code to be inconsistent or inaccurate in type. Summary of the invention
[0003] In order to overcome the shortcomings of the above-mentioned prior art, the present invention provides a method, system and device for automatic code completion based on deep reinforcement learning, which combines code type information with reinforcement learning and constructs a hybrid reward method of immediate reward plus delayed reward to guide code completion and make more precise choices in decision-making. In this way, the system is continuously guided by code type information during the generation process to generate accurate code snippets, saving developers time in processing code and more complex logic, and improving the efficiency of software development and maintenance.
[0004] To achieve the above objectives, one or more embodiments of the present invention provide the following technical solutions:
[0005] In a first aspect of the present invention, one or more embodiments of the present invention provide a method for automatic code completion based on deep reinforcement learning, comprising the following steps:
[0006] Receiving source code data, and converting the source code data into corresponding code type data according to preset rules;
[0007] Inputting the first source code data and the first code type data into a code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning;
[0008] Inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning;
[0009] A deep reinforcement learning network is constructed using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0010] Inputting the third source code data into the policy network, and training the policy network through supervised learning;
[0011] Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning;
[0012] The trained and optimized policy network is used to complete the target source code data.
[0013] In a second aspect of the present invention, one or more embodiments of the present invention further provide a code automatic completion system based on deep reinforcement learning, comprising:
[0014] A data acquisition module, used for receiving source code data and converting the source code data into corresponding code type data according to preset rules;
[0015] A model fine-tuning module, used for inputting the first source code data and the first code type data into the code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning;
[0016] A quality assessment module, configured to input the second source code data and the second code type data into an evaluator model, and train the evaluator model using a hard parameter sharing method of multi-task learning;
[0017] A deep learning module, used to construct a deep reinforcement learning network using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0018] A model training module, configured to input the third source code data into the policy network, and train the policy network through supervised learning; input the fourth source code data and the fourth code type data into the policy network, and train the policy network through deep reinforcement learning;
[0019] The code completion module is used to use the trained and optimized policy network to complete the target source code data.
[0020] In the third aspect of the present invention, one or more embodiments of the present invention further provide a computing device, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein when the processor executes the program, the method for automatic code completion based on deep reinforcement learning as described in the first aspect of the present invention is implemented.
[0021] One or more of the above technical solutions have the following beneficial effects:
[0022] The present invention uses a code automatic completion method, system and device based on deep reinforcement learning to train a type-aware code completion quality evaluator model and construct a novel reward mechanism, so that the code generation process can be guided by code type information, changing the traditional method of only using supervised fine-tuning, so that technicians can handle the complex logic of the code more accurately, thereby improving the efficiency of software development and maintenance. BRIEF DESCRIPTION OF THE DRAWINGS
[0023] The accompanying drawings in the specification, which constitute a part of the present invention, are used to provide a further understanding of the present invention. The exemplary embodiments of the present invention and their descriptions are used to explain the present invention and do not constitute improper limitations on the present invention.
[0024] Figure 1 A flow chart of a method for automatic code completion based on deep reinforcement learning in one or more embodiments of the present invention;
[0025] Figure 2 A schematic diagram of fine-tuning a code completion model in one or more embodiments of the present invention;
[0026] Figure 3 A schematic diagram of training an evaluator model in one or more embodiments of the present invention;
[0027] Figure 4 A schematic diagram of training a policy network in one or more embodiments of the present invention. DETAILED DESCRIPTION
[0028] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0029] It should be noted that the following detailed descriptions are exemplary and are intended to provide further explanation of the present invention. Unless otherwise specified, all technical and scientific terms used herein have the same meanings as those commonly understood by those skilled in the art to which the present invention belongs.
[0030] It should be noted that the terms used herein are only for describing specific embodiments and are not intended to limit exemplary embodiments according to the present invention. As used herein, unless the context clearly indicates otherwise, the singular form is also intended to include the plural form. In addition, it should be understood that when the terms "comprising" and / or "including" are used in this specification, it indicates the presence of features, steps, operations, devices, components and / or combinations thereof.
[0031] In the absence of conflict, the embodiments of the present invention and the features of the embodiments may be combined with each other.
[0032] First, the relevant technical terms involved in the present invention are explained:
[0033] Source code data: The original code used to build software or applications. This code is usually written by developers and converted into machine-executable instructions by a compiler or interpreter. A source code snippet is a portion of a source code statement in a programming language.
[0034] Markov Decision Process: A mathematical framework for describing problems in which decisions are made sequentially in a series of discrete time steps, with each decision affecting future states and rewards.
[0035] Supervised fine-tuning: A common model optimization method in the field of deep learning, which combines supervised learning and fine-tuning techniques. The pre-trained model is applied to a specific supervised learning task. During the fine-tuning process, the model parameters are adjusted according to the labeled data of the specific task to make it perform better on the task.
[0036] Reward: Reward is the signal that the agent gets from the environment after performing an action, which indicates whether the action was good or bad or an evaluation of the agent's behavior. Reward is usually a scalar value that can be positive, negative, or zero, indicating the agent's feedback on the environment's behavior.
[0037] The present invention is based on a deep reinforcement learning mechanism of code type information fusion, and implements the following steps in sequence: first, source code is divided and transformed, a code type prediction dataset is constructed, and a code completion model is fine-tuned using multi-task learning; then, an evaluator model of code completion based on type awareness is trained to generate instant rewards for the intermediate process of completion; finally, the code completion model is jointly trained through supervised fine-tuning and deep reinforcement learning fine-tuning to generate accurate source code snippets, thereby improving the efficiency of software development and maintenance. Embodiment 1
[0038] This embodiment provides a method for automatic code completion based on deep reinforcement learning. Figure 1 As shown, the following steps are included:
[0039] 101. Receive source code data, and convert the source code data into corresponding code type data according to a preset rule;
[0040] In an embodiment of the present invention, publicly available source code data can be obtained from an open platform. For example, taking Python language as an example, converting the source code data according to preset rules may include using a structure analysis module to perform grammatical structure analysis on the Python source code data file, filtering out a number of Python codes with comments, and then using a code detection tool to detect the several Python codes to filter out grammatically correct Python codes.
[0041] In the embodiment of the present invention, Python is also used as an example to process source code data using a Python tokenizer, and the source code is decomposed into a series of tokens. Each token represents an atomic element in the source code, such as a keyword, identifier, constant, operator, etc. For example, in Python code, def, myFunction, =, 5, etc. may all be recognized tokens. The Python tokenizer is used to extract the finest-grained type information for each token, with a total of 58 different types; the types that describe the encoding of Python files are <encoding>, describes the end position of the Python file <endmarker>and description code <comment>Three types of discard; use keyword.iskeyword() function to check and rename Python reserved words <keyword>; According to the CodeXGLUE specification, <newline>(New line), <nl>(new blank or comment line) is converted to <eol>.
[0042] In the embodiment of the present invention, when converting source code data into code type data, the following 12 main code type information are mainly concerned: <name> 、 <number> 、 <string> 、 <indent> 、 <dedent> 、 <errortoken> 、 <endcoding> 、 <endmarker> 、 <comment> 、 <nl> 、 <newline>and <op>.in <op>Type consists of the remaining 46 operation types, such as <less> 、 <greater> 、 <equal> 、 <dot>wait.
[0043] in, <name>Indicates the name, <number>Represents a number, <string>Represents a string, <indent>Indicates indentation. <dedent>Indicates reverse indentation. <errortoken>Indicates an error mark. <endcoding>Indicates the file encoding type. <endmarker>Indicates the end position of the file. <comment>Indicates comments, <nl>Indicates a line break character, <newline>Display new line, <op>Represents an operator.
[0044] It is understandable that, in actual process, the code type information may include the above-mentioned type information and may also include other common code type information not mentioned, and the above-mentioned code type information is only used as an example.
[0045] In an embodiment of the present invention, in order to subsequently train the evaluator model and the code completion model, the present invention integrates the code type information so that the code generation process can be guided by the code type information, thereby improving the accuracy of code completion.
[0046] 102. Input the first source code data and the first code type data into a code completion model, and fine-tune the code completion model by using a hard parameter sharing method of multi-task learning;
[0047] In an embodiment of the present invention, the code completion model may be an existing code completion model, for example, a convolutional neural network (CNN) or a deep convolutional neural network (DCNN) that can be used for code completion, etc.; the code completion model specifically further includes structures such as an input layer, a convolutional layer, a fully connected layer, and an output layer; wherein the input layer is responsible for inputting the state information of the receiving environment, and the input data may need to be preprocessed, such as normalization, dimensionality reduction, etc., to adapt to the input requirements of the network; the output layer is responsible for generating action decisions based on the processing results of the network. For discrete action spaces, the output layer may use a softmax activation function to output the probability distribution of each possible action. For continuous action spaces, the output layer may directly output the parameters of the action (such as mean and standard deviation), and then obtain specific action values by sampling these parameters.
[0048] Based on the above analysis, the first source code data and the first code type data are input into the code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning includes:
[0049] The first source code data and the first code type data are input into the code completion model, and the loss between the two tasks of code prediction and code type prediction is calculated by hard parameter sharing; and the parameters of the code completion model are fine-tuned by minimizing the loss between the two tasks.
[0050] like Figure 2 As shown, the first source code data such as def, c_average, (, …,) , average, =, …, average and the first code type data corresponding to the first source code data such as KEYWORD, NAME, LPAR, …, RPAR, NAME, EQEQUAL, …, NAME are input into the code completion model, and the parameters of the code completion model are fine-tuned according to the loss of the code completion task and the loss of the type completion task.
[0051] Among them, for the first source code data and the first code type data, the parameters of the code completion model θ Loss L MTL Calculation methods include: Calculation code completion model θ Enter the following code dataset d code The code completion task loss caused by this and the calculation code completion model θ Type the following data set into the code d type The type completion task loss brought by ; by minimizing the sum of the two completion task losses, the corresponding loss is obtained. Specifically, the parameters of the code completion model The loss calculation formula is as follows:
[0052] L MTL =argmin ( L code (d code ,θ ) +L type ( d type ,θ )
[0053] in, L MTL represents the loss between the code completion task and the code type completion task, L code (d code ,θ ) indicates that in the code completion model θ Enter the following code dataset d code The loss of code completion tasks caused by d code A code data set including first source code data; L type ( d type ,θ ) indicates that in the code completion model θ Type the following data set into the code d type The loss of code completion tasks caused by d type is a code type data set, including first code type data; the code data set and the code type data set may be derived from the source code data received in step 101, and the code type data converted based on a preset rule; θ Represents a parameter of a code completion model, and is used here to refer to the code completion model.
[0054] 103. Input the second source code data and the second code type data into the evaluator model, and train the evaluator model by using a hard parameter sharing method of multi-task learning;
[0055] In the embodiment of the present invention, Figure 3 As shown, inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning includes:
[0056] 301. Segment the second source code data and the second code type data to obtain an incomplete code segment, an incomplete type segment, a reference code segment, and a reference type segment;
[0057] In an embodiment of the present invention, a part or all of the source code data received in step 101 and the converted code type data are selected as the second source code data and the second code type data; this part of the second source code data and the second code type data includes a complete code segment and a complete code type segment; in this embodiment, these complete code segments and complete type segments are randomly cut at the same corresponding positions and divided into two parts, the first parts are respectively used as the incomplete code segment and the incomplete type segment, and the second parts are respectively used as the reference code segment and the reference type segment.
[0058] 302. Input the incomplete code snippet and the incomplete type snippet into the fine-tuned code completion model, output the predicted code snippet and the predicted type snippet, and calculate the evaluation scores of the incomplete code snippet and the incomplete type snippet using the evaluation indicators between the predicted code snippet and the reference code snippet, and between the predicted type snippet and the reference type snippet;
[0059] In an embodiment of the present invention, the incomplete code snippet and the incomplete type snippet are respectively input into the code completion model after step 102, and the predicted code snippet and the predicted type snippet are output. Then, the evaluation score corresponding to the incomplete code snippet is obtained by calculating the BLEU index by comparing the predicted code snippet with the reference code snippet, and the evaluation score corresponding to the incomplete code snippet is obtained by calculating the BLEU index by comparing the predicted type snippet with the reference type snippet. These two evaluation scores can reflect the generation quality of the corresponding incomplete code snippet and incomplete type code.
[0060] BLEU (Bilingual Evaluation Understudy) is an automatic evaluation metric commonly used to evaluate quality in generation tasks. The core idea of BLEU is to compare the similarity between machine-predicted code snippets and a set of reference code snippets. BLEU evaluates the quality of predicted code snippets by the frequency of n-grams (sequences of n consecutive words) in the output in the reference code snippets. Similarly, the generation quality of code type snippets can also be evaluated using BLEU.
[0061] 303. Input the incomplete code snippet and the incomplete type snippet into an evaluator model to obtain final scores of the incomplete code snippet and the incomplete type snippet;
[0062] In an embodiment of the present invention, the present invention adopts an evaluator model to evaluate the incomplete code snippet and the incomplete type snippet, and the final score reflects the quality of code completion. In this embodiment, GPT-2 can be used as an evaluator model. GPT-2 has a very large scale. It is a huge Transformer-based model trained on a massive data set. A multi-head attention mechanism is used in each Transformer block to enhance the language representation by aggregating previous outputs. Subsequently, a linear layer is used to convert the outputs of multiple attention heads into a final score. Based on the above analysis, the final score is calculated as follows:
[0063] h 0 =H x W e +W p
[0064] h l =TransformerBlock(h l-1 )
[0065] s'=Linear(h l )
[0066] in, h 0 is the hidden state vector of the incomplete code snippet; H x is the context vector of the incomplete code snippet; W e is the token embedding matrix, W p is the position embedding matrix, TransformerBlock is the Transformer block, l ∈[1, L ], L is the number of layers in the Transformer block, h l The incomplete code snippet is in the estimator model l The hidden state vector representation of the layer; Linear is a linear layer, and linear processing of the hidden state vector representation can obtain the corresponding final score. s’ is the final score output by the evaluator model.
[0067] 304. Train the parameters of the evaluator model by calculating and minimizing the mean square error loss between the evaluation scores of the incomplete code snippets and the incomplete type snippets and the corresponding final scores.
[0068] In the embodiment of the present invention, the training goal of the evaluator model is to accurately evaluate the effectiveness of the completed code for subsequent code completion. Therefore, the training goal of the evaluator model in a single task is to minimize the mean square error between the evaluation score and the final score of the incomplete code snippet, and the evaluation score and the final score of the incomplete code type.
[0069] In this embodiment of the present invention, the mean square error loss of the evaluator model is L eva The calculation method includes: calculating the square of the final score of the incomplete code snippet and the final score of the incomplete type snippet in each sample, as well as the square of the evaluation score of the incomplete code snippet and the evaluation score of the incomplete type snippet of each sample; summing the squares of each sample and then averaging them, and minimizing the mean square error sum to obtain the corresponding error mean square loss. Specifically, the calculation formula of the mean square error loss of the evaluator model is as follows:
[0070]
[0071] in, represents the mean squared error loss of the estimator model, represents the number of samples in the training set of the estimator model, and Respectively represent i The final scores of incomplete code snippets and incomplete type snippets in the sample. and Respectively represent i The evaluation scores of incomplete code snippets and incomplete type snippets in the sample.
[0072] 104. Construct a deep reinforcement learning network using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0073] In an embodiment of the present invention, the present invention uses a code completion model to complete code information and code type information, uses code type information to assist in completing code information, and uses an evaluator model to evaluate the generation quality of the code completion model; based on this, using the fine-tuned code completion model and the trained evaluator model to construct a deep reinforcement learning network includes:
[0074] 401. Model the code completion process as a Markov decision process;
[0075] A Markov Decision Process (MDP) consists of states, actions, rewards, and decisions; in the MDP of code completion, the state can be represented as the context of the code snippet currently being written. This can include characters that have been typed, grammatical structures, variable names, function names, type information, etc. The state can also be a higher-level representation, such as a fragment of an abstract syntax tree (AST) or a subgraph of a program dependency graph. Actions correspond to code completion suggestions that can be executed in a given state. For example, if the state represents the beginning of a function call, then actions may include various possible function names, the beginning or end of a parameter list, etc. The reward function defines the value of performing an action in a particular state. In the MDP of code completion, rewards can be defined based on the accuracy and usefulness of the completion suggestions. For example, if a completion suggestion directly corresponds to the code that the developer wants to enter, a higher reward can be given; if the completion suggestion is irrelevant or misleading, a lower reward or penalty can be given. Decisions describe the probability of transitioning from one state to another after executing an action. In the MDP of code completion, these probabilities can be estimated based on training data (e.g., a large existing code base). For example, given a particular function name and the start of an argument list, we can compute the probability of the most likely next argument or the end of the argument list.
[0076] 402. Construct a state space according to the incomplete code fragment and the code fragment sampled and generated during the decoding process, and the incomplete type fragment and the type fragment sampled and generated during the decoding process;
[0077] In the embodiment of the present invention, the time step of decoding the code t In , the current state consists of the incomplete code fragment and the code tokens of the code fragment generated earlier in the decoding process, that is, Similarly, the time step of decoding in code type t In , the current state consists of the incomplete type fragment and the type token of the type fragment generated earlier in the decoding process, that is, .
[0078] in, represents the current decoding state of the code data at time step t, Represents the current decoding status of type data at time step t, It is an incomplete code snippet; It is an incomplete type fragment; Code snippet for downsampling from time step 1 to time step t-1, A type fragment that downsamples from time step 1 to time step t-1.
[0079] 403. Construct an action space based on the code token of the sampled type fragment;
[0080] In the embodiment of the present invention, in the code completion task, each time step t Sampling a token from the vocabulary corresponds to the time step t The downsampled code snippets are used as the code tokens for subsequent predictions. In the code type completion task, each time step t Sampling a token from the vocabulary is the type fragment sampled at the corresponding time step t as the code type token for subsequent prediction.
[0081] 404. Construct a mixed reward space based on the length matching between the code token generated by sampling and the type token generated by sampling;
[0082] In the embodiment of the present invention, the reward design is mainly aimed at using code type information to guide code generation. To achieve this goal, the embodiment of the present invention designs a type-aware code completion quality evaluator model. Since the code tokens generated by the model in the reinforcement learning training data may not match the code type tokens in length. Therefore, for the parts with equal lengths, the evaluator model will give rewards. For the parts with inconsistent lengths, zero rewards are assigned. In addition, the embodiment of the present invention also adopts a mixed reward mechanism of immediate rewards and delayed rewards. For the cutoff symbol < / s >, use the evaluation metric EM as a delayed reward to provide more precise guidance to the policy network.
[0083] The evaluation index may be the EM (Exact Match) index, which is a commonly used evaluation index mainly used in text matching and similarity calculation tasks. The predicted result is compared with the true result, and if the two are exactly the same, the result is calculated as 1, otherwise it is calculated as 0.
[0084] In an embodiment of the present invention, the calculation method of the hybrid reward includes: when the generated code snippet matches the length of the generated type snippet, the hybrid reward is a weighted reward of the final score of the generated code snippet and the final score of the generated type snippet; when the generated code snippet does not match the length of the generated type snippet, the hybrid reward is a zero reward; when the generated code snippet and the generated type snippet are both cut off, the hybrid reward is a weighted reward of the code generation accuracy and the type generation accuracy; wherein the final scores of the generated code snippet and the generated type snippet can be obtained through the evaluator model; when the generated code snippet does not match the length of the generated type snippet, it may be that one of the generated code snippet or the generated type snippet is a cutoff symbol. < / s >, the generated code snippet and the generated type snippet are both cutoff, indicating that the generated code snippet and the generated type snippet are both cutoff < / s >. Through the hybrid reward of the embodiment of the present invention, the code type information can be used to guide the code generation process, generate accurate code snippets, make more precise choices in decision-making, save developers time in processing code and more complex logic, and improve software development and maintenance efficiency.
[0085] Specifically, the calculation formula of the mixed reward in the embodiment of the present invention is expressed as:
[0086]
[0087] Among them, r() represents the mixed reward function, This is a code snippet for downsampling at time step t; is the type fragment sampled at time step t; and is a hyperparameter used to control the reward ratio of codes and code types; is the trained estimator model; It is an incomplete code snippet; is an incomplete type fragment, Code snippet for downsampling from time step 1 to time step t-1, is a type fragment downsampled from time step 1 to time step t-1, so It is the final score output by the evaluator model after evaluating the code snippet generated by downsampling at time step t. It is the final score output by the evaluator model after evaluating the type fragment generated by downsampling at time step t; EM code To calculate the evaluation index of code accuracy; EM tpye It is an evaluation indicator for calculating the accuracy of code type; < / s > indicates a terminator.
[0088] 405. Input the current state into the policy network and output the next state.
[0089] In the embodiment of the present invention, in the code completion task, the corresponding strategy function takes the current state as input and outputs the next state, where the next state is the code token to be completed, that is, the code snippet sampled at the corresponding time step t; in the code type completion task, the corresponding strategy function takes the current state as input and outputs the next state, where the next state is the code type to be completed, that is, the type snippet sampled at the corresponding time step t. The strategy function can use a common probability density function.
[0090] In some embodiments, both policy functions can be obtained by using the probability distribution output by the Softmax function, which is a commonly used function in deep learning, machine learning, and multi-classification problems. Its function is to compress an arbitrary K-dimensional real vector z (where each element in z can be regarded as the original score of a certain category or the output of a linear layer) into a K-dimensional real vector σ(z), where each element in the vector σ(z) is between (0, 1) and the sum of all elements is 1. This allows σ(z) to be interpreted as a probability distribution.
[0091] Based on the above analysis, the strategy function is defined as follows:
[0092]
[0093]
[0094] in, Indicates in status Next Select The probability of Indicates status Next Select The probability of express X and In the case of The probability of express F and In the case of The probability of and is the weight parameter of the policy network, and is the bias vector of the policy network, and is the time step The hidden state of .
[0095] 105. Input the third source code data into the policy network, and train the policy network through supervised learning;
[0096] In the embodiment of the present invention, in the process of supervised learning of the policy network, the code type completion task is abandoned, and only the code completion task is focused on, so only the next code token needs to be predicted, and the next code type token does not need to be predicted. The third source code data is a part of the source code data or all of the source code data received from step 101.
[0097] In the supervised learning training process, such as Figure 4 As shown, the third source code data is input into the policy network, and the predicted generated code data is output; the policy network is trained by optimizing the log-likelihood loss of the input sequence and the output sequence; wherein the log-likelihood loss L sft The calculation method includes: calculating the probability of selecting the next code token, that is, the code fragment sampled at time step t, under the condition of the input sequence and the first t-1 code tokens, that is, the code data fragment corresponding to time step 1 to time step t-1, so as to solve the probability and obtain the corresponding log-likelihood loss; specifically, the log-likelihood loss L sft The calculation formula is expressed as:
[0098]
[0099] in, represents the log-likelihood loss, which is based on the natural logarithm, p θ ( Y|X ) indicates that X Next Select Y The probability of X Indicates an incomplete code snippet. Y Represents the predicted generated code snippet; the training goal of the code completion task based on supervised fine-tuning is to map the input sequence to the output sequence, where the input sequence here can be the third source code data, and the output sequence is the predicted generated code data; the predicted generated code data is used as the predicted token sequence, and the third source code data is used as the real token sequence, and the difference between the token sequence predicted by the model and the real token sequence is minimized; so that the generated token sequence is closer to the real code sequence.
[0100] 106. Input the fourth source code data and the fourth code type data into the policy network, and train the policy network through deep reinforcement learning;
[0101] In the embodiment of the present invention, Figure 4 As shown, the process of training the policy network through deep reinforcement learning may specifically include:
[0102] 601. Segment the fourth source code data and the fourth code type data to obtain an incomplete code segment and an incomplete type segment;
[0103] 602. Sampling the fourth source code data and the fourth code type data to obtain a sampled reinforcement learning code training sample and a sampled reinforcement learning code type training sample;
[0104] 603. Input the sampled reinforcement learning code training samples and the sampled reinforcement learning code type training samples into the policy network, guide the prediction of code snippets through code types, and output the generated code snippets and the generated type snippets;
[0105] 604. The evaluation network processes the incomplete code snippet, the incomplete type snippet, the generated code snippet, and the generated type snippet, thereby providing a corresponding mixed reward; the mixed reward includes an immediate reward when the length of the generated code snippet matches the length of the generated type snippet, and a delayed reward when both the generated code snippet and the generated type snippet are expired;
[0106] In the embodiment of the present invention, the instant reward may refer to an instant reward for each code token and code type token generated, such as R1, R2, ... R n ; The delayed reward may refer to a delayed reward R given when the generated code token and code type token are both cutoffs.
[0107] In a preferred embodiment of the present invention, the hybrid reward is defined according to the trained evaluator model as follows:
[0108] When the length of the generated code snippet matches the length of the generated type snippet, that is, neither the generated code snippet nor the generated type snippet is a cutoff; the mixed reward is a weighted reward of the final score of the generated code snippet and the final score of the generated type snippet, and the weighted weight here can be controlled by two hyperparameters, which can control the reward proportion of code generation and type generation;
[0109] When the length of the generated code snippet does not match the length of the generated type snippet, that is, the generated code snippet or the generated type snippet has a cutoff character, indicating that the lengths of the two do not match, the mixed reward is zero reward, that is, the reward value is 0;
[0110] When both the generated code snippet and the generated type snippet are cutoff, that is, the generated code snippet or the generated type snippet is a cutoff, the mixed reward is the code generation accuracy EM code and type generation accuracy EM tpye Similarly, the weighted reward here can be controlled by two hyperparameters, which can control the reward ratio of code generation and type generation.
[0111] It is understandable that the weighted weights of the two weighted rewards in the above embodiment may be the same or different, and those skilled in the art may adjust them according to actual conditions.
[0112] 605. Use the mixed reward to construct a negative expected return loss, and train the policy network by minimizing the negative expected return loss.
[0113] In the embodiment of the present invention, in the multi-task code completion task, the fine-tuning training goal of the policy network is to find a policy network to minimize the negative expected return, and in the code type completion task, the fine-tuning training goal of the policy network is to find a policy network to minimize the negative expected return, where the negative expected return loss refers to the situation where the cumulative mixed reward obtained after executing a series of code generation and type generation actions is lower than its expected value. Therefore, the negative expected return loss L drl It is to solve the long-term cumulative sum of mixed rewards, and by minimizing the negative expectation, which is the negative of the cumulative sum of mixed rewards, the corresponding negative expected return loss is obtained; wherein, the negative expected return loss L drl The calculation formula is expressed as:
[0114]
[0115] in, X Indicates an incomplete code snippet, which corresponds to multiple different ; F Indicates an incomplete type fragment, which corresponds to multiple different ; Represents sampled reinforcement learning code training samples, which correspond to multiple different sampled generated code snippets , Represents sampled reinforcement learning code type training samples, which correspond to multiple different sampled generated type fragments ; E represents the expected function, Representation sample obey distributed, Representation sample obey distributed; Represents a mixed reward function; through deep reinforcement learning algorithms and policy gradient definitions, the gradient of the non-differentiable regression reward function for:
[0116]
[0117] in, Indicates the gradient of the policy network parameters. Indicates that the code snippet will be incomplete As input, predict the sampled reinforcement learning code training samples The probability distribution of Indicates that the incomplete type fragment is used as input to predict the sampled reinforcement learning code type training sample The probability distribution of .
[0118] 107. Use the trained and optimized strategy network to complete the target source code data.
[0119] In the embodiment of the present invention, after the above training optimization, the policy network can be used to complete the target source code data, and the target source code data can be the source code data received in step 101 or the source code data obtained additionally, which is not specifically limited in this embodiment.
[0120] It should be noted that the terms "first", "second", "third", and "fourth" are only used for descriptive purposes and cannot be understood as indicating or implying relative importance or implicitly indicating the number of indicated technical features. Therefore, the features defined as "first", "second", "third", and "fourth" may explicitly or implicitly include at least one of the features. Taking the first source code data as an example, the first source code data refers to a part or all of the source code data received from step 101, and the second source code data may also refer to a part or all of the source code data received from step 101. The first source code data and the second source code data may be the same or different, and the present invention does not make specific limitations on this.
[0121] It can be understood that the code automatic completion method based on deep reinforcement learning provided by the present application can be used but is not limited to the following application scenarios: when developers write program code, in order to improve the efficiency of program code writing, they can first try to write a part of the code, and then apply the method provided by the present application to the part of the code to complete the part of the code, thereby improving the efficiency of code writing.
[0122] Embodiment 2
[0123] The purpose of this embodiment is to provide a code automatic completion system based on deep reinforcement learning.
[0124] A code auto-completion system based on deep reinforcement learning of code type fusion, including:
[0125] A data acquisition module, used for receiving source code data and converting the source code data into corresponding code type data according to preset rules;
[0126] A model fine-tuning module, used for inputting the first source code data and the first code type data into the code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning;
[0127] A quality assessment module, configured to input the second source code data and the second code type data into an evaluator model, and train the evaluator model using a hard parameter sharing method of multi-task learning;
[0128] A deep learning module, used to construct a deep reinforcement learning network using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0129] A model training module, configured to input the third source code data into the policy network, and train the policy network through supervised learning; input the fourth source code data and the fourth code type data into the policy network, and train the policy network through deep reinforcement learning;
[0130] The code completion module is used to use the trained and optimized policy network to complete the target source code data.
[0131] Embodiment 3
[0132] The purpose of this embodiment is to provide a computing device.
[0133] A computing device comprises a memory, a processor and a computer program stored in the memory and executable on the processor, wherein when the processor executes the program, the following steps are implemented, including:
[0134] Receiving source code data, and converting the source code data into corresponding code type data according to preset rules;
[0135] Inputting the first source code data and the first code type data into a code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning;
[0136] Inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning;
[0137] A deep reinforcement learning network is constructed using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0138] Inputting the third source code data into the policy network, and training the policy network through supervised learning;
[0139] Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning;
[0140] The trained and optimized policy network is used to complete the target source code data.
[0141] Embodiment 4
[0142] The purpose of this embodiment is to provide a computer-readable storage medium.
[0143] A computer readable storage medium having a computer program stored thereon, which, when executed by a processor, performs the following steps:
[0144] Receiving source code data, and converting the source code data into corresponding code type data according to preset rules;
[0145] Inputting the first source code data and the first code type data into a code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning;
[0146] Inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning;
[0147] A deep reinforcement learning network is constructed using the fine-tuned code completion model and the trained evaluator model; the deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model;
[0148] Inputting the third source code data into the policy network, and training the policy network through supervised learning;
[0149] Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning;
[0150] The trained and optimized policy network is used to complete the target source code data.
[0151] The steps involved in the above embodiments 2, 3 and 4 correspond to the method embodiment 1, and the specific implementation methods can refer to the relevant description part of embodiment 1. The term "computer-readable storage medium" should be understood as a single medium or multiple media including one or more instruction sets; it should also be understood to include any medium that can store, encode or carry an instruction set for execution by a processor and enable the processor to execute any method in the present invention.
[0152] One or more of the above embodiments have the following technical effects:
[0153] (1) To address the exposure bias problem of deep learning-based code completion models during prediction, a new hybrid training method was adopted. This method combines deep learning and deep reinforcement learning to jointly train the code completion model, aiming to improve the overall performance of the model.
[0154] (2) Aiming at the problem that the code completion model lacks type information constraints during the generation process, a method, system and device for automatic code completion based on deep reinforcement learning are proposed. In the deep learning stage, the method, system and device adopt a multi-task fine-tuning method of code prediction and type prediction. In the deep reinforcement learning stage, a type-aware evaluator is trained to generate immediate rewards and provide delayed rewards at the end of completion, thus forming a hybrid mode of immediate and delayed rewards.
[0155] Those skilled in the art should understand that the modules or steps of the present invention described above can be implemented by a general-purpose computer device, or alternatively, they can be implemented by a program code executable by a computing device, so that they can be stored in a storage device and executed by the computing device, or they can be made into individual integrated circuit modules, or multiple modules or steps therein can be made into a single integrated circuit module for implementation. The present invention is not limited to any specific combination of hardware and software.
[0156] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. For those skilled in the art, the present invention may have various modifications and variations. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
[0157] Although the above describes the specific implementation mode of the present invention in conjunction with the accompanying drawings, it is not intended to limit the scope of protection of the present invention. Those skilled in the art should understand that various modifications or variations that can be made by those skilled in the art on the basis of the technical solution of the present invention without creative work are still within the scope of protection of the present invention.
[0158] Although embodiments of the present invention have been shown and described, it will be appreciated by those skilled in the art that various changes, modifications, substitutions and variations may be made to the embodiments without departing from the principles and spirit of the present invention, and that the scope of the present invention is defined by the appended claims and their equivalents.< / op> < / newline> < / nl> < / comment> < / endmarker> < / endcoding> < / errortoken> < / dedent> < / indent> < / string> < / number> < / name> < / dot> < / equal> < / greater> < / less> < / op> < / op> < / newline> < / nl> < / comment> < / endmarker> < / endcoding> < / errortoken> < / dedent> < / indent> < / string> < / number> < / name> < / eol> < / nl> < / newline> < / keyword> < / comment> < / endmarker> < / encoding>
Claims
1. A code automatic completion method based on deep reinforcement learning, characterized in that: The steps include: Receiving source code data, and converting the source code data into corresponding code type data according to preset rules; Inputting the first source code data and the first code type data into a code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning; Inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning; Build a deep reinforcement learning network using the fine-tuned code completion model and the trained estimator model; The deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model; Inputting the third source code data into the policy network, and training the policy network through supervised learning; Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning; The trained and optimized policy network is used to complete the target source code data.
2. A method for automatic code completion based on deep reinforcement learning as claimed in claim 1, characterized in that: The types of the code type data include: <name> 、 <number> 、 <string> 、 <indent> 、 <dedent> 、 <errortoken> 、 <endcoding> 、 <endmarker> 、 <comment> 、 <nl> 、 <newline>and <op>;in, <name>Indicates the name, <number>Represents a number, <string>Represents a string, <indent>Indicates indentation. <dedent>Indicates reverse indentation. <errortoken>Indicates an error mark. <endcoding>Indicates the file encoding type. <endmarker>Indicates the end position of the file. <comment>Indicates comments, <nl>Indicates a line break character, <newline>Display new line, <op> Represents an operator.< / op> < / newline> < / nl> < / comment> < / endmarker> < / endcoding> < / errortoken> < / dedent> < / indent> < / string> < / number> < / name> < / op> < / newline> < / nl> < / comment> < / endmarker> < / endcoding> < / errortoken> < / dedent> < / indent> < / string> < / number> < / name> 3. A method for automatic code completion based on deep reinforcement learning as claimed in claim 1, characterized in that: Inputting the first source code data and the first code type data into the code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning includes: The first source code data and the first code type data are input into a code completion model, and the loss between the two tasks of code prediction and code type prediction is calculated by hard parameter sharing; and the parameters of the code completion model are fine-tuned by minimizing the loss between the two tasks.
4. A method for automatic code completion based on deep reinforcement learning as claimed in claim 1, characterized in that: Inputting the second source code data and the second code type data into the evaluator model, and training the evaluator model using a hard parameter sharing method of multi-task learning includes: Segment the second source code data and the second code type data to obtain an incomplete code segment, an incomplete type segment, a reference code segment, and a reference type segment; Input the incomplete code snippet and the incomplete type snippet into the fine-tuned code completion model, output the predicted code snippet and the predicted type snippet, and calculate the evaluation scores of the incomplete code snippet and the incomplete type snippet using the evaluation indicators between the predicted code snippet and the reference code snippet, and between the predicted type snippet and the reference type snippet; Inputting the incomplete code snippet and the incomplete type snippet into an evaluator model to obtain final scores of the incomplete code snippet and the incomplete type snippet; The parameters of the evaluator model are trained by calculating the mean square error loss between the evaluation scores of the incomplete code snippets, the incomplete type snippets and the corresponding final scores.
5. The method for automatic code completion based on deep reinforcement learning according to claim 1, characterized in that: Building a deep reinforcement learning network using the fine-tuned code completion model and the trained estimator model includes: The code completion process is modeled as a Markov decision process. The state space is constructed based on the incomplete code fragments and the code fragments sampled during the decoding process, and the incomplete type fragments and the type fragments sampled during the decoding process. The action space is constructed based on the code tokens of the sampled type fragments. The mixed reward space is constructed based on the length matching between the sampled code tokens and the sampled type tokens. The current state is input into the policy network and the next state is output.
6. A method for automatic code completion based on deep reinforcement learning as claimed in claim 1, characterized in that: Inputting the third source code data into the policy network, and training the policy network through supervised learning includes: The third source code data is input into the policy network, and the predicted generated code data is output; and the policy network is trained by optimizing the log-likelihood loss between the input third source code data and the output generated code data.
7. A method for automatic code completion based on deep reinforcement learning as claimed in claim 1, characterized in that: Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning includes: Segmenting the fourth source code data and the fourth code type data to obtain an incomplete code segment and an incomplete type segment; Sampling the fourth source code data and the fourth code type data to obtain a sampled reinforcement learning code training sample and a sampled reinforcement learning code type training sample; Input the sampled reinforcement learning code training samples and the sampled reinforcement learning code type training samples into the policy network, guide the prediction of code snippets through code types, and output the generated code snippets and generated type snippets; The evaluation network processes the incomplete code snippet, the incomplete type snippet, the generated code snippet, and the generated type snippet, thereby giving a corresponding mixed reward; the mixed reward includes an immediate reward when the length of the generated code snippet matches the length of the generated type snippet, and a delayed reward when both the generated code snippet and the generated type snippet are expired; The negative expected return loss is constructed using the mixed reward, and the policy network is trained by minimizing the negative expected return loss.
8. A method for automatic code completion based on deep reinforcement learning as claimed in claim 7, characterized in that: The calculation formula of the mixed reward is expressed as: Among them, r() represents the mixed reward function, represents the current decoding state of the code data at time step t, Represents the current decoding status of type data at time step t, This is a code snippet for downsampling at time step t; is the type fragment sampled at time step t; and is a hyperparameter used to control the reward ratio of codes and code types; is the trained estimator model; It is an incomplete code snippet; is an incomplete type fragment, Code snippet for downsampling from time step 1 to time step t-1, The type fragment is sampled from time step 1 to time step t-1; is the final score output by the evaluator model after evaluating the code snippet generated by downsampling at time step t. It is the final score output by the evaluator model after evaluating the type fragment generated by downsampling at time step t; To calculate the evaluation index of code accuracy; It is an evaluation indicator for calculating the accuracy of code type; Indicates the terminator.
9. A code automatic completion system based on deep reinforcement learning, which is used to implement the code automatic completion method based on deep reinforcement learning according to any one of claims 1 to 8, characterized in that: include: A data acquisition module, used for receiving source code data and converting the source code data into corresponding code type data according to preset rules; A model fine-tuning module, used for inputting the first source code data and the first code type data into the code completion model, and fine-tuning the code completion model by using a hard parameter sharing method of multi-task learning; A quality assessment module, configured to input the second source code data and the second code type data into an evaluator model, and train the evaluator model using a hard parameter sharing method of multi-task learning; A deep learning module for building a deep reinforcement learning network using the fine-tuned code completion model and the trained estimator model; The deep reinforcement learning network includes a policy network and an evaluation network; the policy network corresponds to the fine-tuned code completion model, and the evaluation network corresponds to the trained evaluator model; A model training module, used for inputting the third source code data into the policy network, and training the policy network through supervised learning; Inputting the fourth source code data and the fourth code type data into the policy network, and training the policy network through deep reinforcement learning; The code completion module is used to use the trained and optimized policy network to complete the target source code data.
10. A computing device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that: When the processor executes the program, the code automatic completion method based on deep reinforcement learning as described in any one of claims 1 to 8 is implemented.
Citation Information
Patent Citations
System and method for a convolutional neural network for multi-label classification with partial annotations
CA3061717A1
Container configuration code completion method, device and equipment based on multi-task learning
CN118151982A
Code completion method and device, electronic equipment and medium
CN118227106A
Pre-training for automating code review activities
US20240160435A1
