Constraint decoding for source code generation

By introducing constraint decoding technology and syntax- and semantic-aware decoders in source code generation, combined with static code analysis, the problem of infeasible source code generation by existing models is solved, achieving more efficient syntax and semantic correctness, and reducing security Vulnerability risk.

CN118871886APending Publication Date: 2024-10-29MICROSOFT TECHNOLOGY LICENSING LLC
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202280091893.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Priority Date
2022-03-07
Filing Date
2022-11-29
Publication Date
2024-10-29

AI Technical Summary

Technical Problem

Existing machine learning models have difficulty generating syntactically and semantically correct candidate sequences in source code generation, resulting in generated source code that may be infeasible or have security vulnerabilities.

Method used

Adopt constraint decoding technology that incorporates token constraints in the decoding process to generate feasible candidate sequences through programming language-based syntax, syntactic correctness, semantic constraints, and static type correctness, using syntax- and semantic-aware decoders and static code analysis tools to prune the search space and ensure the syntactic and semantic correctness of the generated candidate sequences.

Benefits of technology

Computing resources and development time are effectively reduced, and the generated candidate sequences are more likely to be syntactically and semantically correct, reducing the risk of potential defects and security vulnerabilities.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN118871886A_ABST
    Figure CN118871886A_ABST
Patent Text Reader

Abstract

Constraint decoding techniques merge lexical constraints into a beam search in each temporal step of a decoding process to generate feasible candidate sequences that are syntactically and semantically correct. The lexical constraint identifies source code lexical or a sequence of lexical that should appear in the candidate sequence. The lexical constraint is generated by checking whether the lexical predicted at each decoding step is applicable to a partial solution of a programming language-based grammar generation rule, syntactic correctness of a partial sequence, and / or static type correctness.
Need to check novelty before this filing date? Find Prior Art

Description

Background Art

[0001] Machine learning is used to perform a wide variety of tasks that predict an output sequence of data given an input sequence of data. For source code generation, the input sequence represents the context of a partially formed source code segment, and the machine learning model predicts or generates a candidate sequence that completes the partially formed source code segment.

[0002] The machine learning model generates a probability distribution over the vocabulary of source code tokens, which is decoded into partial solutions until one or more candidate sequences are generated. Decoding the most likely candidate sequence is a process of searching all possible partial solutions. The search process is intractable because it grows exponentially. Heuristic search methods (such as beam search) are often used to generate partial solutions and final candidate sequences.

[0003] The beam search uses the probability distribution generated by the decoder to identify the top source code tokens that are most likely to be the next source code tokens in the partial solution. The beam search expands the search by expanding the partial solution with the source code tokens with the highest probability identified by the probability distribution. The search continues to expand the set of partial solutions from the top source code tokens identified by the probability distribution of the model until the search ends.

[0004] Sometimes, beam search does not always generate syntactically and semantically correct source code. Beam search relies on the output probabilities generated by the decoder, which may not always be perfectly calibrated for the target source code program or machine learning task. This results in beam search generating source code that is not feasible for the source code program. Summary of the invention

[0005] This summary is intended to introduce a series of concepts in a simplified form, which will be further described in the detailed description below. This summary is not intended to identify key features or essential features of the claimed subject matter, nor is it intended to be used to limit the scope of the claimed subject matter.

[0006] The constraint decoding technique incorporates word-gram constraints into the beam search at each iteration of the decoding process to generate syntactically and semantically correct feasible candidate sequences. Word-gram constraints identify the required source code words, word-gram sequences, or word-gram values ​​that should appear in the partial solution and ultimately appear in the candidate sequence. Word-gram constraints are generated by checking whether the partial solutions predicted at each decoding step are feasible based on the production rules of the grammar of the programming language, the syntactic correctness of the partial solutions, semantic constraints, and / or static type correctness. The partial solutions with most word-gram constraints are output as candidate sequences. The post-processing engine tests the syntactic correctness and error vulnerabilities of the candidate solutions, and eliminates those candidate solutions that are unlikely to be useful.

[0007] These and other features and advantages will be apparent by reading the following detailed description and examining the associated drawings.It is to be understood that both the foregoing general description and the following detailed description are explanatory only and are not restrictive of the aspects as claimed. BRIEF DESCRIPTION OF THE DRAWINGS

[0008] Figure 1 is a schematic diagram illustrating an exemplary embodiment of a constraint decoding system for source code generation.

[0009] Figure 2 is a schematic diagram illustrating an exemplary configuration of a neural decoder transformer model with attention.

[0010] Figure 3 is a flow chart illustrating a first exemplary method of a syntax and semantics-aware constraint decoding method.

[0011] Figure 4 is a flow chart illustrating a second exemplary method of a syntax and semantics-aware constraint decoding method.

[0012] Figure 5 and Figure 6 is a flow chart illustrating an exemplary method of beam searching using syntax and semantics-aware constraint decoding.

[0013] Figure 7 is a flow chart illustrating an exemplary method for post-processing of candidate sequences generated by syntax- and semantics-aware constrained decoding.

[0014] Figure 8 is a block diagram illustrating a first exemplary operating environment.

[0015] Fig. 9 is a block diagram illustrating a second exemplary operating environment. DETAILED DESCRIPTION

[0016] Overview

[0017] A constrained decoding technique is disclosed that incorporates token constraints at each time step of the decoding process to generate syntactically and semantically correct feasible candidate sequences. Token constraints identify source code tokens or token sequences that should appear in the candidate sequence. Token constraints are generated by checking whether the tokens predicted at each decoding step are feasible based on production rules of the grammar of the programming language of the program, syntactic correctness of partial solutions, semantic constraints, and / or static type correctness. In this way, token constraints prune the search space to more feasible candidate sequences, thereby saving computing resources and developer time.

[0018] In one aspect, the constraint decoding technique is utilized in a code generation system such as, but not limited to, a code completion system. Code completion tracks characters entered into a source code editor and predicts candidate sequences to complete source code constructs (i.e., lines of code, method calls, method names, variable names, etc.) based on the current context of the source code in the editor.

[0019] Beam search is used to generate partial solutions and ultimately candidate sequences. Beam search uses the first k tokens identified from each iteration of the neural transformer model to expand the partial solution with the next tokens that may complete the source code fragment. Beam search generates a search tree, but only retains the first k nodes at each level of reasoning to expand the search. The search ends when the termination condition is met and the partial solution is considered a candidate sequence.

[0020] Beam search relies on the output probabilities of the decoder. The decoder is trained to generate output probabilities based on minimizing the cross-entropy loss, which is not always perfectly calibrated for source code quality criteria such as syntax, semantics, and type correctness. This can lead to candidate sequences that expose potential buggy code and security vulnerabilities.

[0021] To compensate for this limitation, the constraint decoding technique infers constraints based on static code analysis at each time step to select the next tokens (in addition to the output probabilities) to add to the partial solutions that are more likely to cause candidate sequences. The candidate sequences are then analyzed for syntactic correctness and error vulnerability. The candidate sequences that pass these tests are then output in a sorted order.

[0022] Attention now turns to a more detailed description of systems, components, devices, and methods for syntax- and semantics-aware constraint decoding.

[0023] system

[0024] Figure 1 An exemplary system 100 for syntax and semantics-aware constraint decoding is illustrated. The system 100 includes a syntax and semantics-aware decoder 102, a beam search engine 105, a static type code analyzer 112, a separation logic static code analyzer 114, a production rule generator 116, and a post-processing engine / syntax and error vulnerability analyzer 110. The decoder 102 processes an input sequence of word-element embeddings 104 to predict candidate sequences 106. The syntax and error vulnerability analyzer 110 then analyzes the candidate sequences 106 for syntactic correctness and error vulnerability within their local and extended source code contexts 108. Those candidate sequences that fail the analysis are filtered out, and the remaining candidate sequences 118 are sorted by code quality scores.

[0025] The syntax and semantics-aware decoder 102 receives an input sequence representing a context of a source code segment for which a candidate sequence is generated. In one aspect, the decoder 102 is trained to complete a partially formed source code segment and receives as input the context of the partially formed source code segment. The decoder 102 predicts a candidate sequence 106 that is most likely to complete the partially formed source code segment.

[0026] In another aspect, the decoder 102 is part of a sequence-to-sequence model that is trained to transform an input sequence of one domain into an output sequence of another domain. For example, the sequence-to-sequence model can transform a source code snippet written in a first programming language (i.e., first domain) into a corresponding source code snippet written in a different programming language (i.e., second domain), transform a method's documentation string (i.e., first domain) into a corresponding method body (i.e., second domain), and transform a method signature (i.e., first domain) into a corresponding test case (i.e., second domain).

[0027] The syntax and semantics-aware decoder 102 receives token constraints generated by one or more static analysis tools, such as a static type code analyzer 112, a separation logic static code analyzer 114, and a production rule generator 116. The static type code analyzer 112 analyzes a code snippet to determine the types used in the code snippet. A type is a data type that represents an object-oriented class associated with a program construct (e.g., a variable, a method, etc.). Examples of static type code analyzers 112 include Intellisense.

[0028] The separation logic static code analyzer 114 analyzes program code without executing the program and is an inter-program static analyzer. An example of a separation logic static code analyzer 114 is Facebook's Infer. In-program analysis is different because it is performed within a method (also called a program or function). Inter-program static analysis spans multiple files or methods, including all methods in the entire program. Inter-program static code analysis can detect memory safety faults or defects that span multiple files or methods, such as null pointer dereferences and memory leaks, which would be missed if intra-program static analysis was used. Inter-program static code analyzers (such as Infer) are based on separation logic that performs Hall logic reasoning on programs that change data structures. Infer uses the analysis language Smallfoot intermediate language (SIL) to represent programs with a simpler instruction set that describes the operations of the program on a symbolic heap. Infer symbolically executes SIL commands on a symbolic heap according to a set of separation logic proof rules to find program paths with symbolic heaps that violate heap-based properties.

[0029] It should be noted that SIL is different from an intermediate language (such as CIL) that represents instructions that can be transformed into native code. SIL instructions are used for symbolic execution, which is a logic-based proof analysis. SIL instructions are not built to be executed on a processor or CPU, such as CIL instructions.

[0030] The production rule generator 116 relies on the production rules of the grammar of the programming language to predict grammatically correct code to complete the partially written code segmentation. Context-free programming languages ​​rely on their context-free grammars to describe how to construct grammatically correct source code. The context-free grammar G is defined by a 4-tuple, G = (V, T, R, S), where V is a set of non-terminal symbols, T is a set of terminal symbols, R is a set of production rules for the grammar, and S is a starting non-terminal symbol for representing the entire program. Terminal symbols are symbols that appear in the string generated by the grammar. Terminal symbols never appear on the left side of a production rule, but always on the right side. Non-terminal symbols are placeholders for symbol patterns that can be generated by non-terminal symbols. Non-terminal symbols always appear on the left side of a production rule. Production rules are rules for replacing non-terminal symbols. If production rules can be applied regardless of the context of the non-terminal, the grammar is context-free.

[0031] The syntax and error vulnerability analyzer 110 reviews the syntactic correctness and error vulnerability of the candidate sequence 106. Software vulnerabilities are defects caused by weaknesses in the program, which may have a negative impact on the execution of the program, such as security violations. Software vulnerabilities include resource leaks, memory leaks, null pointer dereferences, and concurrency errors, which are difficult to detect deterministically.

[0032] We now turn our attention to the discussion of different configurations of syntactic and semantic-aware decoders.

[0033] Neural Transformer Architecture

[0034] In one aspect, the syntax and semantics-aware decoder 102 is configured as a neural transformer model with attention. The neural transformer with attention is a different type of machine learning model. Machine learning involves the use and development of computer systems that are able to learn and adapt without following explicit instructions by using algorithms and statistical models to analyze patterns in data and draw inferences from them. Machine learning uses different types of statistical methods to learn from data and predict future decisions. Traditional machine learning includes classification models, data mining, Bayesian networks, Markov models, clustering, and visual data mapping.

[0035] Deep learning differs from traditional machine learning because it uses multi-stage data processing through many hidden layers of a neural network to learn and interpret features and the relationships between features. Deep learning embodies neural networks, which is different from traditional machine learning techniques that do not use neural networks. The Neural Transformer model is a type of deep learning that utilizes an attention mechanism. Attention guides the neural network to focus on a subset of features or tokens in the input sequence, thereby learning different representations from different positions of tokens in the input sequence.

[0036] In one aspect, the syntactic and semantic-aware decoder is configured as a neural transformer model with attention configured with only a decoder block, while in another aspect, the decoder can be part of an encoder-decoder configuration of a neural transformer model, where the decoder is coupled with a neural encoder transformer with attention.

[0037] The decoder-only neural transformer model is an autoregressive model that produces output one element at a time based on the output of the previous time step. Code completion is best suited for the decoder neural transformer model because it is an autoregressive task that can predict an ordered sequence of tokens, where the order depends on the previous tokens in the sequence.

[0038] By estimating the conditional probability distribution P(output|input), the decoder model will generate an ordered sequence c of tokens / sub-tokens corresponding to the context of the code snippet C. t (t=0…T) is the conditional response word / subword sequence m t The (t=0…N) prediction is the product of conditional probabilities, as follows:

[0039]

[0040] Figure 2 An exemplary structure of a syntax- and semantic-aware decoder as a neural decoder transformer model is illustrated. In one aspect, the neural decoder transformer model 200 includes an input or embedding layer 202 , one or more decoder blocks 204A, 204B (“ 204 ”), and an output layer 206 .

[0041] The decoder block 204 consists of two layers. The first layer includes a masked multi-head self-attention component 214, followed by a layer normalization component 216. The input of the masked multi-head self-attention component 214 has a residual connection with the layer normalization 216. The output of the layer normalization 216 is input into a feedforward neural network 218, which has a residual connection with the layer normalization component 220. The output of the feedforward neural network 218 is input into the layer normalization component 220. The output of the decoder block 204 is a hidden representation set 221. If there are multiple decoder blocks, the hidden representation set 221 is sent through additional decoder blocks.

[0042] Attention is used to decide which parts of the input sequence are important for each sub-token, especially when decoding long sequences, as the decoder is limited to encoding fixed-size vectors. The attention mechanism collects information about the relevant context of a given sub-token, which is used to identify relationships between tokens in a long sequence, while ignoring other tokens that do not have much influence on a given prediction.

[0043] The masked multi-head self-attention component 214 takes the context tensor 212 and weights the correlation between each token embedding represented in the context tensor by generating an attention weight for each token embedding in the input embedding 208. In one aspect, the attention function is a scaled dot product attention, which is mathematically described as follows:

[0044]

[0045] The input consists of dimensions d k The query Q and key K and dimension d v Q is a matrix containing the query or vector representation of a sub-word in the sequence, K is the vector representation of all words in the sequence, and V is the vector representation of all sub-words in the sequence.

[0046] Query, key, and value with d v The output values ​​are linearly projected h times in parallel and these output values ​​are concatenated to the final value:

[0047] MultiHead(Q,K,V)=Concat(head1,…,head h )W o ,

[0048] Among them head i =Attention(QW i Q ,KW i K ,VW i V ),

[0049] Parameter Matrix and

[0050] After the initial time step, the masked multi-head self-attention component 214 receives the output embedding of the previous time step. The masked multi-head self-attention component 214 masks the output embedding from future time steps. The feed-forward neural network 218 processes each output encoding separately. Layer normalization components 216, 220 are used between layers to normalize the input across features.

[0051] The output layer 206 includes a linear layer 222 and a softmax layer 224. The linear layer 222 projects the vector produced by the decoder stack into a logits vector. The softmax layer 224 then converts the score of the logits vector into a positive normalized probability for each word in the vocabulary.

[0052] The Neural Decoder Transformer model with attention is trained on a training dataset from a large number of source code programs. Each source code program in the training dataset does not need to be written in the same programming language. The training dataset can consist of many source code programs, each of which can be written in a different programming language. Each source code program in the training dataset is encoded into a sequence of tokens and / or sub-tokens. Frequently used elements in a programming language are encoded into tokens, while less frequently occurring elements are encoded into character combinations called sub-tokens. This reduces the need to store large vocabularies and provides better accuracy for out-of-vocabulary tokens.

[0053] From the training dataset, the model learns the syntactic structure of the source code and how to predict the most likely sequence of tokens to complete the partially formed code snippet. In some cases, the model can be further fine-tuned with source code customized for a specific task so that the model's parameters are adjusted for performing that specific task.

[0054] method

[0055] Attention is now directed to a more detailed description of the method for constraint decoding for source code generation and translation in the system. It will be appreciated that, unless otherwise noted, the representative method does not necessarily have to be performed in the order presented or in any particular order. In addition, the various activities described with respect to the method can be performed in a serial or parallel manner, or in any combination of serial and parallel operations. In one or more aspects, the method illustrates the operation of the system and device disclosed herein.

[0056] Go to Figure 3 , an exemplary method of constraint decoding for source code generation is shown. A code snippet or input sequence is obtained to be decoded with an initial set of token constraints for a code generation task. A token constraint is a token, an ordered sequence of tokens, or a list of token values ​​(e.g., types) that should appear in a candidate sequence. (collectively, block 302).

[0057] The input sequence is input to a beam search engine which generates a search space of partial solutions to complete the code snippet at each time step using the decoder neural transformer model. The beam search engine employs a beam search to generate the search space (block 304).

[0058] At each time step, the beam search engine infers or predicts new word-meta constraints in order to narrow or prune the search space to more feasible candidates. The new word-meta constraints are predicted from a static analysis code tool that analyzes the partial solutions as they are generated at each time step of the beam search. The initial constraints are typically user defined and preconfigured before the beam search begins. The static analysis tools run in the background of the source code editor and look at the beam search at each time step. These tools guide the beam search to select the next best word-meta for the partial solution, which is more likely to produce a feasible candidate sequence than relying solely on the output probabilities of the decoder. (collectively referred to as box 306).

[0059] New token constraints are obtained from a static type code analyzer, an inter-procedural code analyzer, and / or a generation rule generator. (collectively referred to as box 306). At each time step, the initial constraints and the new constraints are used to select the next token or tokens for each existing partial solution (box 308). The beam search engine terminates the beam search when all time steps are completed or until it is determined that the token at the end of the sequence is the next best token (box 310). After the beam search is completed, the candidate sequence is output to the post-processing engine (box 312).

[0060] In one aspect, the post-processing engine receives the local and extended contexts of the input sequence and analyzes the candidate sequences for syntactic correctness and error vulnerabilities within the local and extended contexts. In addition to those candidates identified as having error vulnerabilities, those candidates that cannot be successfully compiled are also eliminated. The remaining candidates are sorted based on the degree to which the candidate sequences pass the test. (collectively referred to as box 312).

[0061] Figure 4 Another aspect of the constraint decoding method 400 for source code generation is illustrated. In this aspect, a software development system uses a constraint decoding process to generate candidate codes to complete code snippets. Software development environments are typically used to help software developers (i.e., users, programmers, etc.) develop program code. Software development systems may include source code editors and other tools that developers use to write and test their programs. Some software development systems include a code completion feature that provides assistance when a developer edits code by automatically presenting a list of possible candidate codes based on one or more characters (e.g., letters, symbols, etc.) typed by the developer in the source code editor. A pop-up menu may appear containing several suggested code elements that the developer can utilize. This assistance is beneficial because it speeds up development time and reduces common errors such as typos.

[0062] On the one hand, a source code editor runs a background process to monitor characters that a user enters into a source code program in the editor. The background process continuously updates a syntax tree representing the source code program based on the user's actions in the editor. As the user enters characters, a code completion engine uses beam search and a neural decoder transformer model to generate candidates that are most likely to complete the current code context. The candidates are presented to the developer. The developer can select one of the candidates that was entered into the source code program being developed.

[0063] Go to Figure 4 , a code completion system is configured using a neural decoder transformer model and beam search parameters. The beam search parameters include a beam size, initial constraints, and a termination condition. The beam size is the number of partial solutions evaluated at each time step. The termination condition indicates how the beam search ends (this may be based on a maximum length of a candidate sequence) or when a particular end token (e.g., method end, line end, program end) is predicted as the most likely next token and when most constraints are satisfied (collectively referred to as box 402).

[0064] The code completion system will receive a request for a candidate sequence with a context, which is the current state of the code in the editor when the request is issued (box 404). The code completion system transforms the context into a word-embedded input sequence and a position-embedded input sequence (box 406), and calls beam search to predict a list of candidate sequences for completing the code snippet (box 408). The candidate sequences generated by the beam search are then analyzed for syntactic correctness and error vulnerability. Those candidate sequences that fail the syntactic correctness and error vulnerability tests will be eliminated, and the remaining candidate sequences will be output in a sorted order (box 410).

[0065] Beam Search

[0066] Constrained decoding beam search generates a bundle at each time step t, where a bundle consists of a set of partial solutions also called hypotheses. A hypothesis is a partial solution consisting of an ordered sequence of tokens. The bundle size k is the number of hypotheses generated at each time step.

[0067] A partial solution is constructed from the tokens with the highest probability generated from the model output probability distribution. However, the partial solution may not be syntactically correct at each time step, or may not produce a feasible solution. To this end, the beam search obtains additional token constraints at each time step to prune the search space of the partial solution. The additional token constraints are generated from a static analysis tool that runs as a background process. The static analysis tool provides guidance to the beam search on how to select the next token for each partial solution at each time step. For example, a syntactic check on the assumed current state may require a right bracket. To give another example, suppose there is a method call that is part of the partial solution. In order for the partial solution to be type correct, the type of the receiving token is required. The static type analyzer can generate a list of token constraints for the receiving token based on the type determined by the static type analyzer.

[0068] A word-gram constraint or constraints can be a single word-gram, an ordered sequence of word-grams, or a list of word-gram values ​​(e.g., types). The word-gram constraints are added to the next best word-gram set to be appended to the partial solution at each time step. The next best word-gram set includes the top k word-grams identified from the output probability distribution of the model and all unsatisfied word-gram constraints. However, increasing the number of word-gram constraints will increase the number of partial solutions generated by the beam search and increase its computational complexity. In order to limit the number of partial solutions, a set of banks B0, B1, …, B C To track the number of token constraints satisfied by each partial solution. For C token constraints, each library B i Partial solutions that satisfy the same number of word-unit constraints are grouped together. For example, B0 includes all partial solutions that do not satisfy any word-unit constraints, B1 includes all partial solutions that satisfy one word-unit constraint, and Bc includes all partial solutions that satisfy most word-unit constraints. The beam search then selects a partial solution from each library to expand at each time step. In this way, the number of partial solutions N at each time step is limited to N<2*k+C, which is manageable. The number of libraries corresponds to the given number of constraints, and the size of each library, which is set to floor(k / C), is independent of the time step t. The floor function gives the largest integer less than or equal to k / C.

[0069] The first k tokens are selected from a probability distribution generated by the decoder, which indicates the probability that each token will follow the sequence of tokens immediately preceding it in the partial solution. The probability distribution for each hypothesis in the bundle is contained in a score matrix. The size of the score matrix is ​​k x V T , where k is the bundle size, and V T is the size of the word-meta vocabulary.

[0070] Before the decoding process begins, some token constraints may already be known. For example, a static code analyzer may require the presence of a code token or n-gram in the model output when analyzing a sequence of tokens in a partial solution. An n-gram is an ordered sequence of n tokens. Similarly, a data flow analysis may require the presence of a certain token in a partial solution.

[0071] There are several types of word-gram constraints. Hard constraints require the presence of specific word-grams or ordered sequences of word-grams. A hard single-gram constraint is a single word-gram c that must be present for a partial solution to satisfy the constraint. A hard multi-word or n-gram constraint C = {c0, c1, c2} is used to generate at least one partial solution that contains multiple word-grams in the order in which they appear in the constraint. A hard multi-word constraint is considered satisfied if a partial solution contains all of the word-grams {c0, c1, c2} in order. Soft constraints do not require the presence of specific word-grams, but only that the generated word-grams belong to a set of possible word-grams. A soft constraint is satisfied if at least one partial solution has at least one word-gram from the set of soft constraints.

[0072] The beam search iterates for each time step until the maximum token length of the output sequence is reached or the token at the end of the sequence is determined to be the next best token and all constraints are satisfied. Those partial solutions that satisfy all or most of the constraints are output as candidate sequences.

[0073] Go to Figure 5 , which shows an exemplary method of constrained decoding beam search. Initially, a hard set of constraints can be given to the beam search before the search begins, and the size of the library can be configured (box 502). Given an input word sequence, the neural decoder transformer model is called to generate an initial beam (box 502). The initial beam consists of the top k words with the highest probability in the model vocabulary (box 502).

[0074] At each subsequent time step t (box 504), the next bundle is generated by calling the decoder with the current bundle to generate a new output probability distribution or score matrix (box 506). The beam search determines the next best word-gram to be attached to each partial solution or hypothesis in the current bundle based on the score matrix and the word-gram constraint set (box 508). The word-gram constraint set includes the newly added constraints inferred by one or more static analysis tools using the partial solutions generated at the current time step (box 508). The current bundle is updated to include the expanded partial solutions from each library (box 510). At the end of the last time step, the partial solutions from the current bundle that satisfy most of the word-gram constraints are output as candidate sequences (box 512).

[0075] Go to Figure 6, which shows an exemplary method 600 of constraint decoding. For each partial solution or hypothesis in the current bundle (block 602), one or more static analysis tools running in a background process provide output about the partial solution (block 604). The output identifies additional token constraints specific to the partial solution (block 606). These additional token constraints are added to the existing set of token constraints (block 608).

[0076] The neural decoder transformer model is run on the current bundle to generate an output probability distribution that identifies the token most likely to be attached to each partial solution. The tokens with the top k probabilities are selected to expand the partial solution. (collectively referred to as box 610).

[0077] For each partial solution in the current bundle (block 612), the next best word-gram that expands the partial solution is determined (blocks 614-618). The selection of the next best word-gram takes into account all unsatisfied word-gram constraints that are not currently in the partial solution (block 614) and the word-grams with the top-k probabilities computed by the neural decoder transformer model (block 616). Each partial solution is expanded with its next best word-gram (block 618).

[0078] The expanded partial solutions are then grouped into appropriate bins based on the number of constraints satisfied in the expanded partial solutions (block 620). New bundles are generated by selecting the top partial solutions from each bin, with preference given to bins that satisfy the most constraints (block 622).

[0079] Filtering and sorting of candidate sequences

[0080] Once candidate sequences are generated, the post-processing engine analyzes each candidate sequence against a series of static tests and eliminates failed candidate sequences. Figure 7 , which shows an exemplary method 700 for analyzing the best candidate sequence. The best candidate sequence output from the beam search engine is output to the syntax and error vulnerability analyzer (box 702). For each candidate sequence (box 704), the post-processing engine inserts surrounding context into the candidate sequence, which includes the source code immediately surrounding the source code input of the beam search and the external source code contained in the import statement (box 706).

[0081] The syntax and vulnerability analyzer runs a series of tests on each candidate sequence (box 708). The series of tests includes compiling the candidate sequence in its surrounding context through a compiler or compilation tool, testing whether the compiled code works in the build environment, performing static type checking analysis on the candidate sequence to check whether the code sequence contains any out-of-range types, and using a separation logic static code analyzer to analyze the error vulnerabilities in the candidate sequence. If the separation logic static code analyzer finds any security-critical risks, the relevant candidate sequence is eliminated. All remaining candidate sequences are sorted based on the results of the static analysis test (box 710), and the fewer syntax errors and vulnerabilities found, the higher the candidate sequence is ranked (box 710), and it is output in the sorted order (box 712).

[0082] Exemplary Operating Environment

[0083] In one aspect, a syntax and semantics-aware constraint decoder is used in a code completion system. Figure 8 , the decoder can be embodied as a function or feature integrated into the source code development tool 800, such as a source code editor, an integrated development environment (IDE), a browser, and / or a stand-alone application. Code completion can be embodied as a tool or feature, which can be an add-on, plug-in, extension, and / or component of a source code editor, browser, application, and / or IDE. In one aspect, the source code development tool 800 can include a user interface 802, a parser 804, and a code completion system 806, which includes a syntax and semantics-aware decoder 808, a bundle search engine 810, a syntax and error vulnerability analyzer 812, and a static analysis tool 814.

[0084] The user interface 802 includes a set of features or functions for developing (e.g., writing, editing, testing) source code programs. The user interface 802 may include a window 816 that displays the source code currently in the source code development tool 800. The user interface may utilize a pop-up window 820 to present possible candidate sequences for completion, allowing the developer to browse the candidate sequences and select a candidate sequence from the list. Alternatively, the candidate sequence may appear as a continuation of the current source code program.

[0085] Parser 804 monitors characters input into source code development tool 800 and generates a corresponding syntax tree. Parser 804 also updates the syntax tree as developers create and edit source code in source code development tool 800.

[0086] At certain points in the editing process, the user interface 802 will request candidates from the code completion system 806 to complete the code snippet. The code completion system 806 extracts tokens from the concrete syntax tree and generates a context tensor representing the input sequence, as described above. The code completion system 806 performs a beam search until a termination condition is reached. The top k candidate sequences are returned to the user interface 802.

[0087] If the developer wants to accept the candidate sequence, the developer can type a specific key or key combination to accept the candidate sequence, which is then automatically inserted into the source code program.

[0088] exist Figure 8 816 in source code development tool 800. Code completion system 806 decodes the program to predict candidate sequences to complete the partially formed line of code "api=" at position 818. In this example, decoding begins without any constraints, and after three time steps of beam search, the preferred hypothesis is ["twee", "py", "."]. Static analysis tool 814 running in the background detects method call expressions and infers the type of the receiving token to be "tweepy". Tool 814 suggests a soft constraint requiring the following token to be one of the following: [API, OAuthHandler, client, AppAuthHandler, Paginator, cursor, ...]. The bundle search engine 810 outputs the preferred candidate solutions that satisfy the soft constraints, namely "tweepy.API(auth)" and "tweepy.OAuthHandler(auth)".

[0089] Attention is now directed to a discussion of another exemplary operating environment. Fig. 9 An exemplary operating environment 900 is illustrated in which one or more computing devices 902 are used in the constraint decoding process. However, it should be noted that the aspects disclosed herein are not limited to any particular device configuration. The computing device 902 can be configured to generate a decoder as a cloud service that is distributed to end users, to perform constraint decoding as a cloud service, and / or to perform code completion as a cloud service or part of an application. It should be noted that the operating environment is not limited to any particular configuration and other configurations are possible.

[0090] The computing device 902 can be any type of electronic device, such as, but not limited to, a mobile device, a personal digital assistant, a mobile computing device, a smart phone, a cellular phone, a handheld computer, a server, a server array or server farm, a web server, a network server, a blade server, an Internet server, a workstation, a minicomputer, a mainframe computer, a supercomputer, a network appliance, a web appliance, a distributed computing system, a multiprocessor system, or a combination thereof. The operating environment 900 can be configured in a network environment, a distributed environment, a multiprocessor environment, or a stand-alone computing device that can access a remote or local storage device.

[0091] The computing device 902 may include one or more processors 904, one or more communication interfaces 906, one or more storage devices 908, one or more memory devices 910, and one or more input / output devices 912. The processor 904 may be any commercially available or custom processor, and may include dual microprocessors and multi-processor architectures. The communication interface 906 facilitates wired or wireless communication between the computing device 902 and other devices. The storage device 908 may be a computer-readable medium that does not contain a propagation signal such as a modulated data signal transmitted by a carrier wave. Examples of storage devices 908 include, but are not limited to, RAM, ROM, EEPROM, flash memory or other memory technology, CD-ROM, digital versatile disc (DVD) or other optical storage, cassettes, tapes, disk storage, all of which do not contain a propagation signal such as a modulated data signal transmitted by a carrier wave. There may be multiple storage devices 908 in the computing device 902. The input / output device 912 may include a keyboard, a mouse, a pen, a voice input device, a touch input device, a display, a speaker, a printer, etc., and any combination thereof.

[0092] The memory device or memory 910 can be any non-transitory computer-readable storage medium that can store executable programs, applications, and data. The computer-readable storage medium does not belong to the propagation signal such as the modulated data signal transmitted by the carrier. It can be any type of non-transitory memory device (e.g., random access memory, read-only memory, etc.), magnetic storage, volatile memory, non-volatile memory, optical storage, DVD, CD, floppy disk drive, etc., which does not belong to the propagation signal such as the modulated data signal transmitted by the carrier. The memory 910 may also include one or more external storage devices or remote storage devices, which do not belong to the propagation signal such as the modulated data signal transmitted by the carrier.

[0093] The memory device 910 may include instructions, components, and data. A component is a software program that performs a specific function and is also referred to as a module, program, component, and / or application. The memory device 910 may include an operating system 914, a code generation system 916, a beam search engine 918, a post-processing engine 920 for syntax and error vulnerability analysis, a syntax and semantics-aware decoder 924, a static type code analyzer 926, a rule generator 928, a separation logic static code analyzer 930, one or more compilers 932, a code completion system 934, a source code editor 936, and other applications and data 938.

[0094] The computing device 902 may be communicatively coupled via a network 940. The network 940 may be configured as an ad hoc network, an intranet, an extranet, a virtual private network (VPN), a local area network (LAN), a wireless local area network (WLAN), a wide area network (WAN), a wireless wide area network (WWAN), a metropolitan area network (MAN), the Internet, a portion of a public switched telephone network (PSTN), a plain old telephone service (POTS) network, a wireless network, network, or any other type of network or combination of networks.

[0095] The network 940 may employ a variety of wired and / or wireless communication protocols and / or technologies. The generations of different communication protocols and / or technologies that may be employed by the network may include, but are not limited to, Global System for Mobile Communications (GSM), General Packet Radio Service (GPRS), Enhanced Data GSM Environment (EDGE), Code Division Multiple Access (CDMA), Wideband Code Division Multiple Access (W-CDMA), Code Division Multiple Access 2000 (CDMA-2000), High Speed ​​Downlink Packet Access (HSDPA), Long Term Evolution (LTE), Universal Mobile Telecommunications System (UMTS), Evolution Data Optimized (Ev-DO), Worldwide Interoperability for Microwave Access (WiMax), Time Division Multiple Access (TDMA), Orthogonal Frequency Division Multiplexing (OFDM), Ultra-Wideband (UWB), Wireless Application Protocol (WAP), User Datagram Protocol (UDP), Transmission Control Protocol / Internet Protocol (TCP / IP), any portion of the Open Systems Interconnection (OSI) model protocols, Session Initiation Protocol / Real-time Transport Protocol (SIP / RTP), Short Message Service (SMS), Multimedia Message Service (MMS), or any other communication protocol and / or technology.

[0096] Technical Effects

[0097] Various aspects of the subject matter disclosed herein relate to the technical problem of minimizing the amount of computing resources and execution time required to perform a beam search to generate source code. A technical feature associated with solving this problem is dynamically generated token constraints that are created at each time step of the beam search, and more specifically, are created to guide the beam search to generate feasible candidate sequences. The technical effect achieved is to narrow the search space to more feasible candidate sequences, thereby reducing the computing resources and execution time required to perform the search and develop source code.

[0098] in conclusion

[0099] A system is disclosed, having one or more processors; and a memory. The memory stores one or more programs configured to be executed by the one or more processors. The one or more programs include instructions for performing the following actions: accessing sequence data representing a partially formed source code fragment that is required to be decoded into a complete source code fragment; generating multiple partial solutions as candidates to complete the partially formed source code fragment, the partial solutions including an ordered sequence of word-grams, wherein the word-grams are conditioned on previously generated word-grams; obtaining one or more word-gram constraints from static code analysis of each partial solution; executing a deep learning decoder model to predict word-gram probabilities for each partial solution; generating next word-grams from the word-gram probabilities and from the one or more word-gram constraints to append to each partial solution; extending each partial solution with the next word-gram; and selecting one or more partial solutions that satisfy most word-gram constraints as candidate sequences to complete the partially formed source code fragment.

[0100] In one aspect, static code analysis is based on correct type usage. In one aspect, static code analysis is based on compliance with production rules of the grammar of the programming language of the source code snippet. In one aspect, static code analysis is based on syntactic correctness. In one aspect, a token constraint requires that the following token belongs to a type value list, requires that the following token is a specific token, or requires that the following token is part of an n-gram token.

[0101] In one aspect, one or more programs include instructions for performing the following actions: testing candidate sequences for security vulnerabilities and / or syntactic correctness; and eliminating candidate sequences that fail the security vulnerability test and / or syntactic correctness test. In one aspect, one or more programs include instructions for performing the following actions: sorting candidate sequences based on the results of passing the syntactic and / or error vulnerability test.

[0102] A computer-implemented method is disclosed, comprising: obtaining sequence data representing a source code fragment that is required to be decoded into one or more candidate sequences; obtaining multiple partial solutions for the one or more candidate sequences, the partial solutions comprising an ordered sequence of word-grams, wherein each word-gram is conditioned on a previously generated word-gram; generating a next word-gram to append to each partial solution based on top k word-gram probabilities predicted from a deep learning decoder model and based on one or more word-gram constraints predicted by static code analysis for each partial solution; extending each partial solution with the next word-gram; and selecting at most one candidate sequence for the source code fragment from the extended partial solutions that satisfy most word-gram constraints.

[0103] In one aspect, static code analysis is based on correct type usage. In one aspect, static code analysis is based on compliance with production rules of the grammar of the programming language of the source code fragment. In one aspect, static code analysis is based on syntactic correctness.

[0104] In one aspect, the computer-implemented method further comprises: sorting at least one candidate sequence based on the results of passing the syntax and / or error vulnerability test. In one aspect, the computer-implemented method further comprises: testing at least one candidate sequence for security vulnerability and / or syntactic correctness; and eliminating each candidate sequence in at least one candidate sequence that fails the error vulnerability test and / or syntactic correctness test. In one aspect, the word-gram constraint requires that the next word-gram is a specific word-gram, n-gram, or word-gram of a type from a word-gram type list.

[0105] A computer-implemented method is disclosed, comprising: receiving an ordered sequence of tokens representing a partially formed source code segment that is required to be decoded into a complete source code segment; creating a search space of partial solutions as candidates to complete the partially formed source code segment, wherein the partial solutions include an ordered sequence of tokens, wherein tokens in the ordered sequence are conditioned on previously generated tokens; dynamically generating token constraints from static code analysis of each partial solution; using a deep learning decoder model to generate token probabilities, the token probabilities indicating the likelihood that a token follows a previously generated token; selecting a next token from the token constraints and token probabilities output by the deep learning decoder model to append to each partial solution; searching the search space for one or more partial solutions that contain most of the token constraints; and selecting a selected partial solution from the one or more partial solutions to complete the partially formed source code segment.

[0106] In one aspect, a word-gram constraint requires that the following word-gram be of type value-list. In one aspect, a word-gram constraint requires that the following word-gram be a concrete word-gram. In one aspect, a word-gram constraint requires that the following word-gram be part of an ordered sequence of word-grams.

[0107] In one aspect, the computer-implemented method further comprises: testing the selected partial solutions for syntactic correctness and security vulnerabilities; and sorting the selected partial solutions based on the test results. In one aspect, the computer-implemented method further comprises: testing the selected partial solutions for syntactic correctness and security vulnerabilities; and eliminating the selected partial solutions that fail the test.

[0108] Although the subject matter has been described in language specific to structural features and / or methodological acts, it should be understood that the subject matter defined in the appended claims is not necessarily limited to the specific features or acts described above. Rather, the specific features and acts described above are disclosed as example forms of implementing the claims.

[0109] It will be appreciated that, unless otherwise noted, the representative methods do not necessarily have to be performed in the order presented or in any particular order. In addition, the various activities described with respect to the methods may be performed in a serial or parallel manner, or in any combination of serial and parallel operations. In one or more aspects, the methods illustrate the operation of the systems and devices disclosed herein.

Claims

1. A system comprising: one or more processors; as well as A memory storing one or more programs configured to be executed by the one or more processors, the one or more programs including instructions for performing the following actions: accessing sequence data representing a partially formed source code segment that requires decoding into a complete source code segment; generating a plurality of partial solutions as candidates to complete the partially formed source code fragment, the partial solutions comprising an ordered sequence of tokens, wherein a token is conditioned on a previously generated token; Obtain one or more token constraints from static code analysis of each partial solution; Execute a deep learning decoder model to predict word-token probabilities for each partial solution; generating a next word-gram from the word-gram probabilities and from the one or more word-gram constraints to append to each partial solution; Expanding each partial solution using the next word-gram; as well as One or more partial solutions satisfying most of the word-gram constraints are selected as candidate sequences to complete the partially formed source code fragment.

2. The system of claim 1, wherein the static code analysis is based on correct type usage. 3 . The system of claim 1 , wherein the static code analysis is based on compliance with production rules of a grammar of a programming language of the source code snippet.

4. The system of claim 1, wherein the static code analysis is based on syntactic correctness.

5. The system of claim 1, wherein the word-gram constraint requires the following word-gram to belong to a list of type values, requires the following word-gram to be a specific word-gram, or requires the following word-gram to be part of an n-gram word-gram.

6. The system of claim 1, wherein the one or more programs include instructions for performing the following actions: testing the candidate sequence for security vulnerabilities and / or syntactic correctness; and The candidate sequences that fail the security vulnerability test and / or the syntactic correctness test are eliminated.

7. The system of claim 1, wherein the one or more programs include instructions for performing the following actions: The candidate sequences are ranked based on the results of passing syntax and / or error vulnerability tests.

8. A computer-implemented method comprising: Obtaining sequence data representing source code segments that require decoding into one or more candidate sequences; obtaining a plurality of partial solutions for the one or more candidate sequences, the partial solutions comprising an ordered sequence of word-grams, wherein each word-gram is conditioned on a previously generated word-gram; generating next tokens to append to each partial solution based on the top-k token probabilities predicted from the deep learning decoder model and based on one or more token constraints predicted by static code analysis for each partial solution; Expanding each partial solution with the next word-gram; and At most one candidate sequence is selected for the source code fragment from the expanded partial solutions that satisfy most of the word-gram constraints.

9. The computer implemented method of claim 8, wherein the static code analysis is based on correct type usage.

10. The computer-implemented method of claim 8, wherein the static code analysis is based on compliance with production rules of a grammar of a programming language of the source code snippet.

11. The computer implemented method of claim 8, wherein the static code analysis is based on syntactic correctness.

12. The computer-implemented method of claim 8, further comprising: The at least one candidate sequence is ranked based on results of passing syntax and / or error vulnerability testing.

13. The computer-implemented method of claim 8, further comprising: testing the at least one candidate sequence for security vulnerabilities and / or syntactic correctness; as well as Each candidate sequence of the at least one candidate sequence that fails the security vulnerability test and / or the syntactic correctness test is eliminated.

14. The computer-implemented method of claim 8, wherein the word-gram constraint requires that the following word-gram be a specific word-gram, an n-gram, or a word-gram having a type from a list of word-gram types.

Citation Information

Cited By

  • RAG financial credit decision-making method based on policy mask constraint decoding

    CN121234927A