A multi-task code retrieval method based on modal-independent contrastive learning
By constructing a hybrid modal programming question-answering dataset and modality-independent contrastive learning, the semantic representation alignment capability of the code retrieval model in multi-task scenarios is improved, solving the problem of poor performance of multi-task code retrieval in existing technologies and achieving more efficient multi-task code retrieval results.
Patent Information
- Application Number
- CN202311687907.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2023-12-11
- Publication Date
- 2026-11-20
- Estimated Expiration
- 2043-12-11
AI Technical Summary
Existing code retrieval methods perform poorly in multi-task code retrieval, failing to effectively utilize the semantic representation between text and code modalities, resulting in insufficient generalization ability and performance in multi-task scenarios.
By constructing a large-scale mixed-modality programming question-answering dataset, using a Transformer encoder to build a Siamese network for modality-independent contrastive learning, pre-training a code language representation model, and fine-tuning it on different code retrieval tasks, the model's performance in multi-task code retrieval is improved.
It improves the generalization ability and performance of multi-task code retrieval, enhances the model's learning of matching information in multi-task scenarios, reduces bias in the training and deployment stages, and improves the overall performance of the code retrieval model.
Smart Images

Figure CN117634615B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the interdisciplinary field of code intelligence technology and natural language processing technology, and specifically relates to a multi-task code retrieval method based on modality-independent contrastive learning. Background Technology
[0002] With the increasing number of software developers, code intelligence technology, which leverages artificial intelligence to improve development efficiency, is becoming increasingly important. In practical development work, many programmers hope to use a code search system to find previously written code with similar functionality using natural language for reuse. When students are just starting out in programming, they often encounter problems they cannot solve on their own and need external help. A well-known example of a community for answering programming questions is Stack Overflow, but such communities often suffer from delayed responses. Automated programming question-and-answer technology can greatly improve developer efficiency, and the core of this technology lies in processing programming languages and natural language.
[0003] Unlike generative question-answering systems, retrieval-based question-answering systems offer advantages such as higher reasoning efficiency, greater timeliness, and more flexible knowledge updates and scalability. Early code-pre-trained language models, such as CodeBERT and GraphCodeBERT, typically treated code retrieval as a downstream task to measure the representational ability of the pre-trained model, without specifically designing or improving for the code retrieval technology itself. In the last three years, with the remarkable achievements of contrastive learning in representation learning in computer vision and natural language processing, new techniques using contrastive learning have emerged in the field of code retrieval. For example, ContraCode in 2020 proposed using external tools such as compilers to perturb the code as data augmentation to construct positive examples for contrastive learning pre-training, achieving significant improvements in tasks such as code cloning and type prediction. The UniXCoder model in 2021 also proposed using abstract syntax trees as another representation of code for contrastive learning pre-training among multiple representations, as one of many pre-training tasks. Around the same time, DISCO proposed using bug injection for data augmentation to construct difficult negative examples, thereby improving the effectiveness of contrastive learning and achieving significant gains in code vulnerability detection. In 2022, CodeRetriever proposed a method for constructing pairs of unimodal and cross-modal data from large-scale unsupervised code repositories. Its main idea is to utilize multiple pre-trained text and code retrieval models for data mining, cleaning, and annotation. Existing methods are often optimized for specific retrieval tasks, but their performance in multi-task code retrieval is often insufficient. Summary of the Invention
[0004] To overcome the shortcomings of existing technologies in multi-task code retrieval, this invention provides a multi-task code retrieval method based on modality-independent contrastive learning. By using modality-independent contrastive learning, the semantic representation spaces between the two modalities of text and code are better aligned, thereby improving the model's performance in the field of multi-task code retrieval.
[0005] To achieve the above objectives, the technical solution adopted by the present invention is as follows:
[0006] By constructing a large-scale mixed-modality programming question-answering dataset, data from different modalities are treated as different external representations of the same meaning. A Siamese network is built based on a Transformer encoder. Through contrastive learning-style pre-training on question-answer pairs where code and text intersect, the matching information between the two modalities, code and text, is learned more efficiently, resulting in a code language representation model. This pre-trained code language representation model is used as initialization and fine-tuned on training data from different code retrieval tasks to obtain a multi-task code retrieval model. The trained code retrieval model is then used to encode and vectorize the code corpus, resulting in a code representation vector index library. The code retrieval model is deployed on terminal devices, and text queries are encoded in a streaming manner to obtain text representation vectors. Multi-task code retrieval is achieved through vector maximum inner product search. Through these steps, the model's performance in multi-task code retrieval is effectively improved.
[0007] The specific steps of this method are as follows:
[0008] Step 1: Construct a high-quality programming question-answering dataset ProCQA through remote supervision, including preprocessing, filtering, and deduplication of the corpus;
[0009] (1) Data preprocessing: Raw data was crawled and downloaded from the StackOverflow website using web crawling technology and stored in XML format. Each data entry included structured information from the webpage, mainly divided into two categories, distinguished by type identifier numbers. Type identifier number 1 represented question data, including the question title and description; type identifier number 2 represented answer data, including the user's answer. The BeautifulSoup library was used to parse the raw data, removing HTML tags from the text and retaining the original text and code. Each question record had a corresponding answer number recognized by the user, and each answer data also had a corresponding question number. The raw data after processing was organized into a structured JSON format, with different programming languages divided into different data subsets. Each subset was divided into training, validation, and test sets in an 8:1:1 ratio.
[0010] (2) Data Filtering: In this type of programming question-and-answer community based on social networks, the accuracy of many answers is difficult to guarantee. Directly retaining all question-and-answer pairs on the website will affect the quality of the dataset. This invention uses some meta-information of the StackOverflow website itself to filter the data. Only those answers recognized by the questioner are retained. Considering that short texts do not contain effective information and that the maximum text length supported by most pre-trained language models is limited, such as the longest sequence length supported by BERT being 512, this invention filters out texts with more than 2048 characters or less than 20 characters. The crawled data is classified according to the question tag information provided by the StackOverflow website, and question-and-answer pairs of different programming languages are integrated into different datasets. The final number of all retained question-and-answer pairs is about five million, and this dataset is denoted as ProCQA.
[0011] (3) Data Deduplication: The question-answer pairs in the dataset were collected from StackOverflow, which overlaps with the sources of some commonly used evaluation sets. To prevent data pollution and ensure the fairness of the dataset, downstream evaluation data of ProCQA was deduplicated. Three evaluation sets with the same source as ProCQA, namely CoNaLa, SO-DS, and StaQC, were the main targets for deduplication. All text queries in the test sets of these three datasets were used as candidate samples. If a training sample in the dataset was duplicated with any candidate sample, the training sample was removed from the dataset. Two methods were used to determine whether samples were duplicated. The first method was based on... The first method is a string matching deduplication algorithm. This algorithm iterates through each sample in the training set, and if a sample contains any substring that appears in the downstream evaluation set, it is considered to have duplicated content. The second method is a fuzzy matching deduplication algorithm based on MinHash. The MinHash algorithm constructs a series of hash functions for all n-grams in a text, mapping them to a fixed-length set of hash values, and uses the Jaccard similarity coefficient between the hash sets as the proportion of duplicate content between the two texts. Let the hash value sets corresponding to the n-gram sets of the two problem texts be A and B, respectively, then the formula for calculating the Jaccard similarity between the two is:
[0012]
[0013] When this proportion exceeds a certain threshold, the pair of samples is identified as duplicate samples. This invention uses thresholds of n=3 and 0.8 for deduplication, and uses 128 different hash functions. The results show that approximately 3,000 samples (0.5% of the total samples) in the Python subset are duplicates of text queries in the evaluation set, while the proportion of duplicate samples in the subsets of other languages is extremely small.
[0014] Step 2: Initialize the basic code language model GraphCodeBERT as parameters and construct a Transformer-based Siamese encoder network. For the code retrieval task, perform modality-independent contrastive learning incremental pre-training on the programming question-answering corpora of different languages constructed in Step 1 to obtain a better code language representation model; specifically including the following sub-steps:
[0015] (1) Data sampling is performed from the question-answer pair datasets of different languages constructed in step 1 to obtain batch data B for model training, containing n question-answer pairs:
[0016] B = {(q1,a1),(q2,a2),...,(q n ,a n )}
[0017] Where, q n Let a represent the data for the nth question. n This represents the nth answer data; based on the calculated sampling distribution, there are m data sources, each corresponding to a different subset of programming languages, and the number of question-answer pairs in each data source is n1,…,n. m So, what is the probability p of sampling from the i-th data source? i for:
[0018]
[0019] Where i and j are two positive integers representing the sequence number of the data source;
[0020] (2) The questions and answers are preprocessed by word segmentation, special character concatenation, and vectorization, serving as input for the subsequent code text representation model; given the collected question and answer pairs, each text segment is encoded in UTF-8, and then a WordPiece-based word segmenter is called to divide the input sentence into a word sequence:
[0021]
[0022] Where q represents a single question, and a represents the answer to that question. and These represent the k-th word in a single question and the l-th word in a single answer, respectively.q and l a These are the number of words contained in a single question and a single answer, respectively. Next, the word segmentation results for a single question and a single answer are concatenated with the two special characters [CLS] and [SEP] to obtain the input text sequences for a single question and a single answer, respectively.
[0023]
[0024] Where [CLS] represents the start position of the text sequence, and [SEP] represents the end position of the text sequence;
[0025] (3) Encode the questions and answers separately using a code language model based on a dual-tower architecture; the code language model based on a dual-tower architecture consists of two basic code language models with shared parameters, used to obtain the sentence-level contextual representation vectors of the input text sequences of a single question and answer. The specific steps are as follows:
[0026] The input text sequence X is converted into a sequence of word IDs using the vocabulary of a code language model. Based on the sequence length, a positional encoding ID sequence of appropriate length is assigned to the input text sequence. The converted word ID sequence and the positional encoding ID sequence are then input into the encoder to obtain a word-level context representation matrix. A pre-trained code language model based on the Transformer architecture is used as the encoder in a dual-tower architecture to process the text sequence X of a single question. q Inputting the code language model yields the representation matrix of the last layer:
[0027]
[0028] Where d is the dimension of the row vectors in the representation matrix of the code language model, and l is the sequence length. Represents the real number space; after computation by multiple Transformer layers, the encoder obtains a word-level representation matrix H with contextual information for the input text sequence. q The resulting representation matrix is:
[0029]
[0030] in, These represent the context representation vectors corresponding to [CLS] and [SEP], respectively. This represents the contextual representation vector corresponding to the i-th word in the problem;
[0031] Mean pooling is performed on the context representation vectors of different words to obtain a fixed-length vector representation of the entire sequence.
[0032]
[0033] Similarly, we can obtain a vector representation of the answer text sequence:
[0034]
[0035] Among them, l q and l a These represent the number of words contained in a single question q and a single answer a, respectively, which is the sequence length;
[0036] (4) Calculate the distribution of question-answer similarity scores and estimate the probability of the true answer; in order to model the semantic distance between two vectors in the vector space, use the cosine similarity of the two vectors to calculate the relevance between the question and the answer:
[0037]
[0038] Where s(q,a) represents the similarity between the question and the answer, and ||q||2 represents the L2 norm of the question representation vector, i.e. ||a||2 represents the L2 norm of the vector in the answer representation;
[0039] The calculated scores are then subjected to Softmax normalization to obtain the retrieval probability distribution p(a|q) of the correct answer a:
[0040]
[0041] Where τ is the temperature coefficient, and a' represents the answer that does not match question q. This represents the set of all answers that do not match question q; these answers are denoted as negative samples or negative examples. Since the number of negative samples in the entire corpus is too large to dynamically calculate the representation of all negative samples, we use... As The estimate;
[0042] (5) Calculate the improved approximate contrastive learning loss and train the Siamese encoder network; use negative log-likelihood as the training loss function:
[0043]
[0044] Where n represents the batch size of the data, and p(a|q) represents the probability of finding the correct answer a for question q;
[0045] In estimating the probability distribution of the correct answer, we take the following approach: The approximation strategy is to use the answers to other questions within the same batch, i.e. The objective function corresponding to the approximation strategy is the InfoNCE loss function:
[0046]
[0047] The negative sample is expanded to include different problems within the same batch as negative samples. The corresponding contrastive learning loss function is:
[0048]
[0049] Symmetrically, we obtain the matching loss function for the answer to the question:
[0050]
[0051] Will and The negative sample set is merged to obtain a more sufficient negative sample approximation function. The pre-training loss function corresponding to this approximation strategy is:
[0052]
[0053] Pre-training is performed on the programming question-and-answer dataset obtained in step 1 to obtain a code language representation model;
[0054] Step 3: Fine-tune the pre-trained code language representation model from Step 2 on supervised data for different code retrieval tasks to obtain a multi-task code retrieval model; the specific steps are as follows:
[0055] (1) The natural language text and code pairs in the code library are preprocessed to transform them into sequences of words in the code language model vocabulary, which serve as inputs for the subsequent code retrieval model. First, the natural language text t and code c are segmented into different words using a word segmenter and concatenated with special characters at the beginning and end to obtain the following input sequence:
[0056]
[0057] Among them, l t and l c These represent the lengths of the natural language text t and the code c, respectively.
[0058] (2) Fine-tune the code retrieval model on the training data; encode the code and text using the Transformer-based code language representation model LM respectively, to obtain the corresponding text representation vector t and code representation vector c:
[0059] t = MeanPooling(LM(X) t )),
[0060] c = MeanPooling(LM(X)c )).
[0061] Next, cosine similarity is used to calculate the similarity between the text and the code vector:
[0062] s(t,c)=cos(t,c)
[0063] Using manually labeled data as tags, the code retrieval model is fine-tuned using a contrastive learning loss function similar to that in step 2:
[0064]
[0065] Wherein, the temperature coefficient τ = 0.01;
[0066] Step 4: Apply the multi-task code retrieval model trained in Step 3 to the corresponding code retrieval task to perform multi-task code retrieval; specifically, this includes the following sub-steps:
[0067] (1) Encode each piece of code c in the code repository using the code retrieval model trained in step 3 to obtain the code representation vector c, and then regularize it using the vector's L2 norm, i.e.:
[0068]
[0069] All code representation vectors are stored on the hard disk, and a code representation vector index library is built using Faiss technology;
[0070] (2) Deploy the code retrieval model on the GPU to perform streaming encoding of the text query; during inference, call the encoder to obtain the vector representation of the user text query t'. The most similar code c is retrieved by performing a maximum inner product search on the representation vector index of the regularized code corpus. * As a return value:
[0071]
[0072] in, Represents the collection of all code. This is the vector representation of code c after regularization.
[0073] The advantages of this invention compared to the prior art are:
[0074] 1. Enhanced generalization ability in multi-task scenarios. This invention proposes to construct a large-scale programming question-answering dataset from the StackOverflow community and combine it with the CodeSearchNet corpus built from GitHub for joint pre-training, making the data distribution in the pre-training corpus more diverse and covering a wider range; at the same time, the sampling distribution is smoothed based on the square root of the data size in each subset to avoid bias in the model's learning caused by different data sizes.
[0075] 2. Improved performance in multi-task code retrieval where multiple matching signals need to be utilized simultaneously. In the modality-independent contrastive learning used in this invention, both the question and the answer contain information from both text and code modalities. This hybrid modality data structure enables the model to learn cross-modal and intra-modal matching information more efficiently, thereby improving multi-task code retrieval performance.
[0076] 3. The code retrieval model exhibits less bias during training and deployment. This invention proposes a novel contrastive learning strategy by merging negative sample estimation methods in the existing InfoNCE loss function. This strategy triples the number of negative samples in the traditional objective function and further ensures the utilization rate of negative samples by combining a data parallel strategy, effectively reducing bias during the training and inference deployment stages. Attached Figure Description
[0077] Figure 1 This is a flowchart of a multi-task code retrieval method based on modality-independent contrastive learning according to the present invention. Detailed Implementation
[0078] The present invention will be further described below with reference to the accompanying drawings and examples.
[0079] This invention is a multi-task code retrieval method based on modality-independent contrastive learning, the method as follows: Figure 1 As shown, this invention first proposes constructing a large-scale weakly supervised programming question-answering dataset using remote supervision, and employing filtering and deduplication methods to ensure data quality and fairness. Then, based on this dataset, modality-independent contrastive learning pre-training is performed to better align the semantic representation spaces of text and code modalities. Next, the model is fine-tuned on supervised data for downstream tasks to obtain a code retrieval model. The trained model is then vectorized into a code repository, and multi-task code retrieval is achieved through streaming encoding and vector search of queries. This invention is compared with previous state-of-the-art methods on three code retrieval tasks and demonstrates significant performance improvements.
[0080] The multi-task code retrieval method based on modality-independent contrastive learning proposed in this invention mainly consists of the following steps:
[0081] Step 1: Construct a high-quality programming question-answering dataset ProCQA through remote supervision, including preprocessing, filtering, and deduplication of the corpus;
[0082] (1) Data Preprocessing: Raw data was crawled and downloaded from the StackOverflow website using web crawling technology and stored in XML format. Each data entry contained a lot of structured information from the webpage, mainly divided into two categories, distinguished by type identifier numbers. Type identifier number 1 represents question data, including the question title and description; type identifier number 2 represents answer data, including the user's answer. The BeautifulSoup library was used to parse the raw data, removing HTML tags from the text and retaining the original text and code. Each question record has a corresponding answer number recognized by the user, and each answer data also has a corresponding question number. The raw data after preprocessing was organized into a structured JSON format, with different programming languages divided into different data subsets. Each subset was divided into training, validation, and test sets in an 8:1:1 ratio.
[0083] (2) Data Filtering: In these programming question-and-answer communities based on social networks, the accuracy of many answers is difficult to guarantee. Directly retaining all question-and-answer pairs on the website will affect the quality of the dataset. This invention uses some meta-information of the StackOverflow website itself to filter the data. Only those answers recognized by the questioner are retained. Considering that short texts do not contain effective information and that the maximum text length supported by most pre-trained language models is limited, such as the longest sequence length supported by BERT being 512, this invention filters texts with more than 2048 characters or less than 20 characters. The crawled data is classified according to the question tag information provided by the StackOverflow website, and question-and-answer pairs about different programming languages are integrated into different datasets. The final number of all retained question-and-answer pairs is about five million, and this dataset is denoted as ProCQA.
[0084] (3) Data Deduplication: The question-answer pairs in the dataset were collected from StackOverflow, which partially overlaps with the sources of some commonly used evaluation sets. To prevent data pollution and ensure the fairness of the dataset, downstream evaluation data of ProCQA is deduplicated. Three evaluation sets with the same source as ProCQA, namely CoNaLa, SO-DS, and StaQC, are the main targets for deduplication. All text queries in the test sets of these three datasets are used as candidate samples. If a training sample in the dataset is duplicated with any candidate sample, the training sample is removed from the dataset. This invention uses two methods to determine whether samples are duplicated. The first method is based on... The first method is a string matching deduplication algorithm. This algorithm iterates through each sample in the training set, and if a sample contains any substring that appears in the downstream evaluation set, it is considered to have duplicated content. The second method is a fuzzy matching deduplication algorithm based on MinHash. The MinHash algorithm constructs a series of hash functions for all n-grams in a text, mapping them to a fixed-length set of hash values, and uses the Jaccard similarity coefficient between the hash sets as the proportion of duplicate content between the two texts. Let the hash value sets corresponding to the n-gram sets of the two problem texts be A and B, respectively, then the formula for calculating the Jaccard similarity between the two is:
[0085]
[0086] When this proportion exceeds a certain threshold, the pair of samples is identified as duplicate samples; the thresholds of n=3 and 0.8 are used for deduplication, and the number of different hash functions used is 128; the results show that about 3,000 samples in the Python subset (accounting for 0.5% of the total number of samples) are duplicates of the text queries in the evaluation set, while the proportion of duplicate samples in the subsets of other languages is very small.
[0087] Step 2: Initialize the basic code language model GraphCodeBERT as parameters and construct a Transformer-based Siamese encoder network. For the code retrieval task, perform modality-independent contrastive learning incremental pre-training on the programming question-answering corpora of different languages constructed in Step 1 to obtain a better code language representation model; specifically including the following sub-steps:
[0088] (1) Sample data from the question-answer pair datasets of different languages constructed in step 1 to obtain batch data B for model training, containing n question-answer pairs:
[0089] B = {(q1,a1),(q2,a2),...,(q n ,a n )}
[0090] Where, q n Let a represent the data for the m-th question. n This represents the nth answer data;
[0091] The sampling distribution is calculated as follows: There are m data sources, each corresponding to a different subset of programming languages. The number of question-answer pairs in each data source is n1, ..., a. m So, what is the probability p of sampling from the i-th data source? i for:
[0092]
[0093] Where i and j are two positive integers representing the sequence number of the data source;
[0094] (2) The questions and answers are preprocessed by word segmentation, special character concatenation, and vectorization, serving as input for the subsequent code text representation model; given the collected question and answer pairs, each text segment is encoded in UTF-8, and then a WordPiece-based word segmenter is called to divide the input sentence into a word sequence:
[0095]
[0096] Where q represents a single question, and a represents the answer to that question. and These represent the k-th word in a single question and the l-th word in a single answer, respectively. q and l a These are the number of words contained in a single question and a single answer, respectively. Then, the word segmentation results for a single question and a single answer are concatenated with the two special characters [CLS] and [SEP] to obtain the input text sequences for a single question and a single answer, respectively.
[0097]
[0098] Where [CLS] represents the start position of the text sequence, and [SEP] represents the end position of the text sequence;
[0099] (3) Encode the questions and answers separately using a code language model based on a dual-tower architecture; the code language model based on a dual-tower architecture consists of two basic code language models with shared parameters, used to obtain the contextual representation of the input text sequence of a single question and answer at the sentence level, the specific steps of which are as follows:
[0100] The input text sequence X is converted into a sequence of word IDs using the vocabulary of a code language model. Based on the sequence length, a positional encoding ID sequence of appropriate length is assigned to the input text sequence. The converted word ID sequence and the positional encoding ID sequence are then input into the encoder to obtain a word-level context representation matrix. A pre-trained code language model based on the Transformer architecture is used as the encoder in a dual-tower architecture to process the input text sequence X for a single question. q Inputting this language model yields the vector representation of the last layer.
[0101]
[0102] Where d is the dimension of the row vectors in the representation matrix of the code language model, and l is the sequence length. Represents the real number space; after computation by multiple Transformer layers, the encoder obtains a word-level representation matrix H with contextual information for the input text sequence of a single question. q The resulting representation matrix is:
[0103]
[0104] in, These represent the context representation vectors corresponding to [CLS] and [SEP], respectively. This represents the contextual representation vector corresponding to the i-th word in the problem;
[0105] Mean pooling is performed on the context representation vectors of different words to obtain a fixed-length vector representation of the entire sequence.
[0106]
[0107] Similarly, a vector representation of the answer text sequence can be obtained:
[0108]
[0109] Among them, l q and l a These represent the sequence lengths of a single question q and a single answer a, respectively.
[0110] (4) Calculate the distribution of question-answer similarity scores and estimate the probability of the true answer; in order to model the semantic distance between two vectors in the vector space, use the cosine similarity of the two vectors to calculate the relevance between the question and the answer:
[0111]
[0112] Where s(q,a) represents the similarity between the question and the answer, and ||q||2 represents the L2 norm of the question representation vector, i.e. ||a||2 represents the L2 norm of the vector in the answer representation;
[0113] The calculated scores are then subjected to Softmax normalization to obtain the retrieval probability distribution p(a|q) of the correct answer a:
[0114]
[0115] Where τ is the temperature coefficient, and a' represents the answer that does not match question q. This represents the set of all answers that do not match question q; these answers are denoted as negative samples or negative examples. Since the number of negative samples in the entire corpus is too large to dynamically calculate the representation of all negative samples, we use... As The estimate;
[0116] (5) Calculate the improved approximate contrastive learning loss and train the Siamese encoder network; use negative log-likelihood as the training loss function:
[0117]
[0118] Where n represents the batch size of the data, and p(a|q) represents the probability of finding the correct answer a for question q;
[0119] In estimating the probability distribution of the correct answer, the approach taken is... The approximation strategy is to use the answers to other questions within the same batch, i.e. The objective function corresponding to the approximation strategy is the InfoNCE loss function:
[0120]
[0121] The negative sample is further expanded to include different problems within the same batch, i.e. The corresponding contrastive learning loss function is:
[0122]
[0123] Symmetrically, we obtain the matching loss function between the answer and the question.
[0124]
[0125] Will and The negative sample set is merged to obtain a more sufficient negative sample approximation function. The pre-training loss function corresponding to this approximation strategy is:
[0126]
[0127] Pre-training is performed on the programming question-and-answer dataset obtained in step 1 to obtain a code language representation model;
[0128] Step 3: Fine-tune the pre-trained code language representation model from Step 2 on supervised data for different code retrieval tasks to obtain a multi-task code retrieval model; the specific steps are as follows:
[0129] (1) The natural language text and code pairs in the code library are preprocessed to transform them into sequences of words in the code language model vocabulary, which serve as the input for the subsequent code retrieval model. First, the natural language text t and code c are segmented into different words using a word segmenter and then concatenated with special characters at the beginning and end to obtain the following input sequence:
[0130]
[0131] Among them, l t and l c These represent the lengths of the natural language text t and the code c, respectively.
[0132] (2) Fine-tune the code retrieval model on the training data; encode the code and text using the Transformer-based code language representation model LM respectively, to obtain the corresponding text representation vector t and code representation vector c:
[0133] t = MeanPooling(LM(X) t )),
[0134] c = MeanPooling(LM(X) c )).
[0135] Next, cosine similarity is used to calculate the similarity between the text and the code vector:
[0136] s(t,c)=cos(t,c)
[0137] Using manually labeled code, the same contrastive learning loss function as in step 2 is used to fine-tune the code retrieval model:
[0138]
[0139] Wherein, the temperature coefficient τ = 0.01;
[0140] Step 4: Apply the code retrieval model trained in Step 3 to the corresponding code retrieval task to perform multi-task code retrieval; specifically, this includes the following sub-steps:
[0141] (1) Use the code retrieval model trained in step 3 to encode each piece of code c in the code library to obtain the code representation vector c, and then use the vector's L2 norm to regularize it, that is:
[0142]
[0143] All code representation vectors are stored on the hard disk, and a code representation vector index library is built using Faiss technology;
[0144] (2) Deploy the code retrieval model on the GPU to perform streaming encoding of the text query; during inference, call the encoder to obtain the vector representation of the user text query t'. The most similar code c is retrieved by performing a maximum inner product search on the representation vector index of the regularized code corpus. * As a return value:
[0145]
[0146] in, Represents the collection of all code. This is the vector representation of code c after regularization.
[0147] The method proposed in this invention is denoted as Multi-task Code Retrieval (MTCR). Consistent with CodeRetriever, it uses the GraphCodeBERT model to initialize the parameters. This invention conducts experiments on three code retrieval tasks: text-to-code retrieval, cross-language code retrieval, and cross-domain code retrieval, and compares the proposed method with the best methods on the corresponding datasets.
[0148] Consistent with previous evaluations of retrieval-based code question-answering models, this invention uses three popular retrieval metrics: MRR, R, and MAP, to evaluate the model's retrieval results. Assuming there are N queries in the test set, the retrieval model allows returning the top K most similar answers as output. MRR (Mean Reciprocal Rank) measures the overall performance of the ranking results, and the formula is as follows:
[0149]
[0150] Among them, rank iThis represents the rank of the first correct answer among the predicted results for the i-th question. We define rank as follows: when none of the current K most similar answers contain a correct answer. i →∞.
[0151] MAP (Mean Average Precision) takes into account the ranking information of all correct answers. For a question q, if there are M correct answers, the average precision is obtained by averaging the results of dividing each correct answer by its ranking among all correct answers and its ranking among all candidate answers. We assume that the rankings of these M correct answers among all candidate answers, from smallest to largest, are rank1,...,rank1. M ,but:
[0152]
[0153] The average AP score obtained from multiple queries is the MAP, which reflects the overall retrieval performance of the retrieval model for all correct answers.
[0154]
[0155] R(Recall) measures the model's ability to recall correct answers, representing the proportion of correct answers recalled from the top K results out of the total number of correct answers. The formula is as follows:
[0156]
[0157] Consistent with previous work, the results of R@{1, 5, 10} are compared in this embodiment of the invention.
[0158] As shown in Table 1, in the text-to-code retrieval task, the proposed method MTCR achieves a significant improvement across all programming languages compared to its base model GraphCodeBERT. Furthermore, compared to the previous best model, CodeRetriever, the proposed method also achieves an average improvement of 2.1 points.
[0159] Table 1. MRR Comparison of Different Models on the CodeSearchNet Text Retrieval Task
[0160]
[0161] Table 2 shows the performance of different models on the cross-language code-to-code retrieval task. It can be seen that MTCR significantly outperforms the previous best baseline model, UniXCoder. This confirms that the pre-training method proposed in this invention can better align semantics within the code representation spaces of different languages.
[0162] Table 2 Comparison of MAP of different models on the CodeNet cross-language code retrieval task.
[0163]
[0164] Table 3 compares the out-of-domain generalization performance of different models on programming languages not seen in the two pre-training stages. The GraphCodeBERT model itself achieves better results than models based on CodeBERT for MAML. Compared to GraphCodeBERT, the MTCR method proposed in this invention shows significant improvements across all metrics.
[0165] Table 3 Performance comparison of different models on cross-domain code retrieval tasks
[0166]
[0167]
[0168] The above provides a detailed description of a multi-task code retrieval method based on modality-independent contrastive learning disclosed in this invention. Specific examples have been used to illustrate the principles and implementation methods of this invention. However, those skilled in the art should understand that these are merely illustrative examples, and various changes or modifications can be made to these implementation methods without departing from the principles and implementation of this invention. Therefore, the scope of protection of this invention is defined by the appended claims.
Claims
1. A multi-task code retrieval method based on modality-independent contrastive learning, comprising the following steps: Step 1: Construct a high-quality programming question-answering dataset ProCQA through remote supervision, including preprocessing, filtering, and deduplication of the corpus; The preprocessing operations include: crawling and downloading raw data using web crawling technology; classifying the raw data into two categories using type identifier numbers: type identifier number 1 represents question data, including the question title and description; type identifier number 2 represents answer data, including user answers; parsing the raw data using the BeautifulSoup library; and organizing the preprocessed raw data into a structured JSON format, dividing it into different data subsets for different programming languages, with each subset divided into training, validation, and test sets in an 8:1:1 ratio. The filtering operation includes using the website's own metadata to filter the raw data, retaining the answers that are accepted by the questioner; text with more than 2048 characters or less than 20 characters will be filtered out; then, question-and-answer pairs about different programming languages will be processed and integrated into different datasets. The deduplication operation includes deduplicating downstream evaluation data of ProCQA using a string matching-based deduplication algorithm and a fuzzy matching deduplication algorithm based on MinHash. Step 2: Initialize the network using the base code language model GraphCodeBERT as parameters, construct a Transformer-based Siamese encoder network, and perform modality-independent contrastive learning incremental pre-training on the programming question-answering datasets of different languages constructed in Step 1 for the code retrieval task; specifically including the following sub-steps: (1) Sample data from the question-and-answer pairs dataset in different languages constructed in step 1 to obtain batch data B for model training, including n question-and-answer pairs: B={(q1,a1),(q2,a2),...,(q n ,a n )} Where, q n Let a represent the data for the nth question. n This represents the nth answer data; data sampling is performed based on the calculated sampling distribution. There are m data sources, each corresponding to a different subset of data in a different programming language. The number of question-answer pairs in each data source is n1, ..., n. m The probability p of sampling from the i-th data source i for: Where i and j are two positive integers representing the sequence number of the data source; (2) The questions and answers are preprocessed by word segmentation, special character concatenation, and vectorization, serving as input for the subsequent code text representation model; given the collected question and answer pairs, each text segment is encoded in UTF-8, and then a WordPiece-based word segmenter is called to divide the input sentence into a word sequence: Where q represents a single question, and a represents the answer to that single question. and These represent the k-th word in a single question and the l-th word in a single answer, respectively. q and l a These are the number of words in a single question and a single answer, respectively. Next, the segmented sequence results of a single question and a single answer are concatenated with the two special characters [CLS] and [SEP] to obtain the input text sequence of a single question and a single answer: Where [CLS] represents the start position of the text sequence, and [SEP] represents the end position of the text sequence; (3) Encode the questions and answers separately using a code language model based on a dual-tower architecture; the code language model based on a dual-tower architecture consists of two basic code language models with shared parameters, used to obtain the sentence-level contextual representation vectors of the input text sequences of a single question and a single answer. The specific steps are as follows: The input text sequence X is converted into a word ID sequence using the vocabulary of a code language model. Based on the sequence length, a positional encoding ID sequence of appropriate length is assigned to the input text sequence. The converted word ID sequence and the positional encoding ID sequence are then input into the encoder to obtain a word-level context representation matrix. A pre-trained code language model based on the Transformer architecture is used as the encoder in a dual-tower architecture to process the input text sequence X for a single question. q Inputting this code into the language model yields the representation matrix of the last layer: Where d is the dimension of the row vectors in the representation matrix of the code language model, and l is the sequence length. Represents the real number space; after computation by multiple Transformer layers, the encoder obtains a word-level representation matrix H with contextual information for the input text sequence. q The resulting representation matrix is: in, These represent the context representation vectors corresponding to [CLS] and [SEP], respectively. This represents the contextual representation vector corresponding to the i-th word in the problem; By performing mean pooling on the context representation vectors of different words, a fixed-length vector representation of the entire sequence is obtained: Similarly, we can obtain a vector representation of the answer text sequence: Among them, l q and l a These represent the number of words contained in a single question q and a single answer a, respectively, which is the length of the sequence; (4) Calculate the distribution of question-answer pair similarity scores and estimate the probability of the true answer; use the cosine similarity of the two vectors to calculate the relevance between the question and the answer: Where s(q,a) represents the similarity between the question and the answer, and ||q||2 represents the L2 norm of the question representation vector, i.e. ||a||2 represents the L2 norm of the vector in the answer representation; Softmax normalization is applied to the calculated scores to obtain the retrieval probability p(a|q) of the correct answer a: Where τ is the temperature coefficient. Let a' represent the set of all answers that do not match question q. yes The estimate; (5) Calculate the improved approximate contrastive learning loss and train the Siamese encoder network; use negative log-likelihood as the training loss function: Where n represents the batch size of the data, and p(a|q) represents the probability of finding the correct answer a for question q; In estimating the probability distribution of the correct answer, the first step is to take a... The approximation strategy is to use the answers to other questions within the same batch, i.e. The objective function corresponding to the approximation strategy is the InfoNCE loss function: The negative sample is expanded to include different problems within the same batch as negative samples, i.e. The corresponding contrastive learning loss function is: Symmetrically, we obtain the matching loss function for the answer to the question: Will and The negative sample set is merged to obtain the negative sample approximation function, and the corresponding pre-training loss function is: Pre-training is performed on the programming question-and-answer dataset obtained in step 1 to obtain a code language representation model; Step 3: Fine-tune the pre-trained code language representation model from Step 2 on supervised data for different code retrieval tasks to obtain a multi-task code retrieval model; the specific steps are as follows: (1) The natural language text and the code in the code library are preprocessed separately and transformed into a sequence of words in the vocabulary of the code language model, which serves as the input for the subsequent code retrieval model. First, the natural language text t and the code c are segmented into different words using a word segmenter and concatenated with special characters at the beginning and end to obtain the following input sequence: Among them, l t and l c These represent the lengths of the natural language text t and the code c, respectively. (2) Fine-tune the code retrieval model on the training data; encode the code and text using the Transformer-based code language representation model LM respectively, to obtain the corresponding text representation vector t and code representation vector c: t=MeanPooling(LM(X t )), c=MeanPooling(LM(X c )). Next, cosine similarity is used to calculate the similarity between the text and the code vector: s(t,c)=cos(t,c) Using manually labeled data as tags, the code retrieval model is fine-tuned using a contrastive learning loss function similar to that in step 2: Wherein, the temperature coefficient τ = 0.01; Step 4: Apply the multi-task code retrieval model trained in Step 3 to the corresponding code retrieval task to perform multi-task code retrieval; specifically, this includes the following sub-steps: (1) Encode each piece of code c in the code repository using the code retrieval model trained in step 3 to obtain the code representation vector c, and then regularize it using the vector's L2 norm, i.e.: All code representation vectors are stored on the hard disk, and an index library of code representation vectors is built using Faiss technology; (2) Deploy the code retrieval model on the GPU to perform streaming encoding of the text query; during inference, call the encoder to obtain the vector representation of the user text query t'. The most similar code c is retrieved by performing a maximum inner product search on the representation vector index of the regularized code corpus. * As a return value: in, Represents the collection of all code. This is the vector representation of code c after regularization.
2. The multi-task code retrieval method based on modality-independent contrastive learning according to claim 1, characterized in that: In step 1, a large-scale, high-quality programming question and answer dataset is constructed based on the programming question and answer community.
3. The multi-task code retrieval method based on modality-independent contrastive learning according to claim 1, characterized in that: In step 2, modality-independent contrastive learning pre-training is performed using mixed modal data to obtain a code language representation model.
4. The multi-task code retrieval method based on modality-independent contrastive learning according to claim 1, characterized in that: In step 4, the code retrieval model fine-tuned using supervised data and the pre-encoded code representation vector index library are deployed on the terminal computing device for streaming query processing and multi-task code retrieval.
