Elamur Research

InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees

Paper · 2020 · Nghi D. Q. Bui, Yijun Yu and Lingxiao Jiang

Summary

Software frequently comes with enough structure for a parser to recognize what its parts are, even when there are no labels saying what the software does. InferCode uses that structure to learn a reusable representation of source code. It turns each snippet into an abstract syntax tree, which records how expressions, statements, and other constructs fit together. It then asks a neural network to predict pieces of that tree from a single vector representing the whole snippet. The authors’ intuition is that programs with similar behavior frequently share small structural patterns. Their example is bubble sort, where different implementations can compare neighboring array elements using the same expression pattern even when their identifiers differ.

The prediction targets come from the tree itself. InferCode collects fragments rooted at constructs such as expressions, declarations, and conditions, alongside individual keyword nodes. A tree-based convolutional neural network processes the input, drawing on both the types of its nodes and their text. An attention mechanism combines the node representations into a fixed-length vector. The authors pretrain this encoder on Java-Large, a collection containing 4 million Java files. SrcML supplies a shared vocabulary of syntax node types for the languages considered in the study, allowing the Java-trained encoder to receive trees for other languages. The authors release the implementation and trained embeddings under the InferCode name.

The evaluation puts the learned representation to work in two ways. With the encoder kept fixed, InferCode leads the reported clustering comparisons on both the C and Java datasets, reaching an Adjusted Rand Index of 0.70 on OJ. Its vectors also give the best reported F1 among the unsupervised clone detectors on BigCloneBench and OJClone, with scores of 0.75 and 0.64, respectively. In code-to-code search across Java, C#, C++, and C, it leads each language column in the Mean Reciprocal Rank results. These tests use class assignments, known clone pairs, or known matches to judge the output. The encoder learns without those labels.

For the supervised tasks, the authors use the pretrained weights as a starting point for fine-tuning. With all the available labeled training data, InferCode reaches 98.0% accuracy on OJ classification and 43.33% F1 on Java-Small method naming. Both scores improve on the corresponding randomly initialized network and are close to the specialized baselines ASTNN and Code2seq, respectively. Further comparisons help explain the transfer results. Predicting subtrees works better than predicting individual tokens or method names on the three tasks tested, and combining node types with node text works better than relying on either input alone. The results show that a training objective derived from syntax can support several different uses of the same representation.

Deep dive: InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees

InferCode learns reusable code vectors by predicting syntax subtrees and tests them on clustering, clone detection, search, and supervised tasks. · about 35 minutes to read

The problem and its context

A representation trained for one job may travel poorly

A source file can answer different questions depending on what a reader needs. Someone looking for an existing implementation wants to compare what two snippets do. Someone organizing solutions to programming exercises wants to discover which implementations belong together. Someone naming a method wants a phrase that describes the work done by its body. A code embedding, the term the paper uses for a vector representation of a snippet, gives each of these applications a common kind of input. The design question is what evidence the vector should preserve before any of those applications gives it a specific job.

The paper describes a typical code-learning pipeline as having two parts. The first converts source into an intermediate representation. It could be a sequence of tokens, a tree, a collection of paths through a tree, or a graph whose edges express chosen relationships. The second part is an encoder, a network that reads that representation and produces a vector. Training connects the vector to a prediction objective. For example, if the objective rewards getting a method name right, the encoder learns to preserve evidence that helps with naming. The usefulness of the same vector for grouping algorithms depends on how much the signals for the two tasks overlap.

Getting those training signals can be expensive. A dataset for functionality classification needs assignments to functionality classes. A supervised clone detector needs examples of snippets that count as clones and examples that do not. Feature engineering can add another cost when a task calls for an intermediate representation with particular kinds of dependency edges. Unlabeled source code is abundant on the hosting platforms the paper names. Its usefulness for pretraining depends on finding an objective that can be applied before a person or a task-specific process supplies those annotations.

The unit of code is a second design issue. A method may suit a naming benchmark, but a code search query might be a shorter snippet or a file. A representation that exists only as a lookup for a fixed set of units cannot directly produce a vector for a new unit of a different size. InferCode’s authors make parsing the interface. If the parser can turn the supplied unit into a tree, the same encoding procedure can process it. The distinction is between learning a reusable function that produces vectors and storing a vector for each member of a training collection.

The authors cite a study of Code2vec that illustrates another distinction. That study reused pretrained token embeddings and found that they performed poorly on other tasks, including against simpler word-embedding approaches. A token vector represents one kind of input to an encoder. InferCode instead proposes to reuse the resulting vector for a whole tree or to transfer the weights of the encoder that produces it. The comparison motivates testing transfer at the level where information about a snippet has already been combined.

What trees contribute

Turning source into tokens preserves its text in sequence. Turning it into an abstract syntax tree, or AST, exposes the nesting that gives those tokens their grammatical roles. A comparison may sit inside a condition, which in turn belongs to a larger statement. A declaration may contain a smaller expression. Two snippets can differ in spelling while sharing parts of this arrangement. The tree makes it possible to identify a recurring pattern at the scale of a single expression, even when the surrounding statements look different.

Earlier systems in the paper also use ASTs. Code2vec represents a method through a collection of paths and trains the resulting vector for method naming. Code2seq also uses paths, with a representation that supports generation of a textual description of code. ASTNN works with smaller statement-level trees derived from an AST. These systems establish the usefulness of decomposing a tree for learning. InferCode changes the role of the pieces. An extracted fragment becomes something to predict during pretraining, while the encoder receives the tree for the whole input snippet.

Graph-based work starts from richer connections. In Learning to Represent Programs with Graphs, dependencies are added as edges between tree nodes, with the aim of exposing information about the program beyond the tree’s parent–child relations. The InferCode paper also discusses approaches based on execution traces. Both are ways to give a learner evidence that can be difficult to recover from a plain tree. The authors’ choice is driven by availability and portability. A parser supplies trees directly, while a graph may require a choice of which dependencies to add and a way to recover them in every language of interest. The paper identifies task-specific type inference as an example where the graph’s edges can be closely tied to the application.

That tradeoff defines the experiment. The paper asks how much a network can learn from the structure already available in an AST. Its two bubble-sort implementations are an example of where the idea is plausible. The indices in the array comparisons differ, but the relationship between an array access and its neighbor recurs. The authors extend that intuition to a large collection, where many trees can supply examples of similar local constructs. The hypothesis concerns useful statistical evidence for code similarity. A tree fragment can participate in that evidence even when it provides only a small part of the information needed to understand a program.

How unlabeled examples supply a prediction task

The relevant idea from self-supervised learning is to derive the answers to a training task from the inputs. The paper calls the automatically obtained answers pseudo-labels and the training problem a pretext task. Visual examples in the related work include applying a rotation and asking a network to recover it, or using color as the answer when the input is grayscale. In both cases, the original data supply the supervision. What matters for transfer is the intermediate representation the network learns while solving the imposed problem.

The closest analogy in natural language processing is Doc2vec. Its document vector is trained to be predictive of words observed in the document. The approach extends an idea behind Word2vec, where learning draws on the occurrence of words in local contexts. The paper also places this work alongside approaches that predict neighboring sentences or recover masked words, as in BERT. These examples share the use of an automatically available signal, while differing in what they ask a representation to preserve.

Source-code research had already explored text embeddings and self-supervision for particular applications. The authors mention earlier uses of document embeddings with code tokens or node types and a program-repair approach designed around its own task. InferCode takes the document analogy in a structural direction. The full AST plays the role of a document, and its selected subtrees play the role of words. The representation is trained to anticipate those fragments without knowing whether it will later be used to compare code, retrieve a match, or make a labeled prediction.

The method, step by step

Turn a snippet into an input and a set of targets

Every training example starts with source code that SrcML can parse. The resulting tree supplies two views of the same example. The complete tree goes to the encoder. A traversal of the tree identifies the fragments the encoder will be trained to predict. Both operations see the same underlying snippet. The method learns through the requirement to compress the tree into a vector that is predictive of its fragments. It does not face a separate task of filling in syntax removed from the input.

The training procedure looks for selected node types during traversal. When a node qualifies, its subtree is taken with that node as the root. The experiments use roots of type expr_stmt, decl_stmt, expr, and condition, representing expression statements, declaration statements, expressions, and conditions. The paper also includes single-keyword nodes like if, for, and while as targets. This gives the vocabulary entries at different levels of detail, without making each entire conditional or loop body a prediction target.

A declaration in the bubble-sort example shows why the fragments can overlap. The declaration int n = arr.length is a selected piece, and the expression arr.length inside it is another selected piece. The larger unit gives evidence about the part the expression plays. The smaller one can recur independently in other contexts. Another example contrasts int n = arr.length with int m = x.length. Their names differ, but they share a declaration structure and the operation of accessing a length. The method uses both structural and textual features, so the example motivates learning across such variation without assuming that every change in names will leave a vector unchanged.

The choice of roots controls a practical property of the objective. A whole loop with its body may produce a very specific target that appears rarely elsewhere. It can also vary for reasons that have little bearing on what two implementations have in common. Expressions and conditions give the learner more opportunities to see a recurring construction across examples. Single-keyword targets make a coarser fact available as well, such as the presence of a loop construct. The authors pool the selected subtrees from the training corpus into a vocabulary. Each entry has a trainable vector, so predicting a fragment means scoring a vocabulary item, instead of generating a new tree.

How InferCode learns and reuses code vectors

The steps in order.

How InferCode learns and reuses code vectorsStep 1: Parse source into an abstract syntax tree1. Parse source into an abstract syntax treeStep 2: Extract target subtrees and build their vocabulary2. Extract target subtrees and build their vocabularyStep 3: Initialize nodes from types and text3. Initialize nodes from types and textStep 4: Apply tree convolutions to compute node states4. Apply tree convolutions to compute node statesStep 5: Pool node states with learned attention5. Pool node states with learned attentionStep 6: Predict observed subtrees from the code vector6. Predict observed subtrees from the code vectorStep 7: Reuse the trained encoder or transfer its weights7. Reuse the trained encoder or transfer its weights

From predicting words to predicting subtrees

The mathematical analogy starts with a document and a sampled word from it. In the version of Doc2vec described in the paper, a document has its own trainable vector. A word also has a vector. The score for a particular word comes from the dot product of the two vectors, which is larger when their coordinates align in the learned space. The scores are converted into probabilities across the word vocabulary.

Pr(wᵢⱼ | dᵢ) = exp(vᵢ · vᵢⱼ) / Σ_{w ∈ 𝒱} exp(vᵢ · v(w))

Here dᵢ is document i, and wᵢⱼ is the word at sampled position j in that document. vᵢ is the document’s vector, vᵢⱼ is the vector of the sampled word, and v(w) is the vector of a candidate word w in vocabulary 𝒱. The centered dot is the vector dot product, exp is exponentiation with the natural base, and Σ sums the contributions of all vocabulary words. ∈ means membership in the vocabulary. Pr denotes probability, and the bar separates the word being predicted from the document on which the prediction is conditioned.

Σⱼ log Pr(wᵢⱼ | dᵢ)

Here Σⱼ adds the terms over sampled positions j for a fixed document dᵢ. log is the logarithm, and Pr(wᵢⱼ | dᵢ) is the conditional probability assigned to the sampled word wᵢⱼ in document i. Maximizing this sum rewards a document vector that assigns probability to the words observed in that document. The sum captures the supervision available from multiple words in the same input.

InferCode makes a corresponding prediction for fragments observed in a tree. Its key change is how it obtains the counterpart of the document vector. For a snippet, the vector is computed by running the tree through the encoder. There is no need to add a learned lookup entry for each new snippet. Training changes the shared encoding function, so a tree encountered after training can be processed by the same function.

Σⱼ log Pr(Tᵢⱼ | Tᵢ)

In this expression, Tᵢ is the AST for training example i, Tᵢⱼ is its selected subtree at index j, and Pr(Tᵢⱼ | Tᵢ) is the probability assigned to that subtree given the input tree. log takes the logarithm and Σⱼ sums across the selected targets of this example. The paper presents the objective as maximization of this log likelihood. Several fragments from a single tree thus provide training signals for the same whole-snippet vector.

The paper also states the general self-supervised objective as a mean loss over examples. That formulation clarifies the separation between generating a target and fitting a predictor. The pseudo-labels can be obtained before the network learns anything, using the same selection rule throughout the dataset.

loss(𝒟) = (1 / n) Σ_{i=1}^n loss(Xᵢ, Pᵢ)

𝒟 denotes the training collection, n is the number of training examples, and i indexes them from 1 through n. Xᵢ is the input for instance i, and Pᵢ is its automatically generated supervision. loss(Xᵢ, Pᵢ) measures the prediction error for that example. Σ adds the errors and 1 / n takes their mean, giving the collection-level loss(𝒟) to minimize. In InferCode the input is the AST, and the supervision consists of its selected subtrees.

Give each node both a type and a textual feature

A tree has more information than its outline. Nodes can represent roles such as operators or statements, and nodes can carry the text associated with them. A node type says what kind of construct the parser recognized. The text gives the encoder evidence about the particular construct in this instance. For instance, an expression node and the text nested inside it convey different aspects of the same region of source. InferCode learns embeddings for both kinds of input and combines them through a linear layer to produce the initial node vector.

T = (V, E, X)

T denotes the input tree, V is its set of nodes, E is its set of parent–child edges, and X is the set of features associated with the nodes. The parentheses group the three parts of the tree. Each node has an initial real-valued vector of dimension D, where D is the width of the representation. The notation W_type and W_token refers to the trainable embedding parameters for node types and text tokens, respectively. The initial vector comes from fusing those embeddings. It supplies the starting features for the hidden state, the representation of a node used inside the network.

This feature choice is one of the paper’s changes to the original tree-based convolutional neural network, abbreviated TBCNN. The original initialization discussed by the authors uses type information. The extended initialization gives the network access to vocabulary that a purely structural view would discard. At the same time, it preserves the type even when different source fragments use different text. The study separately tests the consequences of each source of evidence, since a good result for the final system alone would give little guidance about the value of the fusion.

Move information through the tree

A tree convolution processes a local arrangement of nodes. The authors describe a window emulated as a binary tree, with weight matrices associated with top, left, and right positions. A node’s effective weight within a window is a mixture of those matrices. The mixture coefficients depend on depth and position. This lets a single set of parameter matrices be applied to windows occurring in different trees, while preserving a role for the position of each node. The computation transforms the node features, adds their contributions, and passes the result through a nonlinear function.

K = 2ᵈ − 1

Here d denotes the depth of the window as counted in the paper, and K is the number of nodes in the corresponding binary window, including the top node. The base 2 comes from the binary arrangement, and the superscript denotes the power d. Subtracting 1 gives the stated window size. This describes the window in the convolution formula. The input from SrcML is the original AST.

y = tanh(Σᵢ₌₁ᴷ (ηᵢᵗ Wₜ + ηᵢˡ Wₗ + ηᵢʳ Wᵣ)xᵢ + b)

y is the output vector for the convolution window, and tanh is the hyperbolic tangent applied to its coordinates. Σᵢ₌₁ᴷ sums over the window’s K nodes, from node 1 through node K. xᵢ is the D-dimensional input feature vector at node i. Wₜ, Wₗ, and Wᵣ are trainable D by D matrices for the top, left, and right positions. The corresponding ηᵢᵗ, ηᵢˡ, and ηᵢʳ are the positional coefficients for node i. The sum inside the parentheses forms the matrix applied to xᵢ, and b is the D-dimensional bias vector added before the nonlinearity.

The paper describes the encoding process as an accumulation from descendants toward parents. After the network has processed a node’s tree context, its hidden state can carry information about the construct and about the smaller constructs underneath it. In the declaration example, the node representing the larger statement has access to information from inside that statement, while the nested expression also has its own state. The next stage can use both. This matters because the training target vocabulary includes fragments at more than one level, and downstream tasks may draw on evidence from several parts of the tree.

Pool a tree of variable size into one vector

Trees for different snippets have different numbers of nodes. The downstream procedures need vectors of the same width, so InferCode aggregates the states into one vector. The original TBCNN discussed in the paper uses max pooling. The authors replace it with learned attention. For every node, the attention layer scores its hidden state against a single learned vector. A softmax, which converts scores to positive weights that sum to one, makes those scores relative to the other nodes of the same input tree.

αᵢ = exp(hᵢ · a) / Σ_{j=1}^n exp(hⱼ · a)

αᵢ is the attention weight for node i. hᵢ is that node’s D-dimensional state, hⱼ is the state for node j, and a is the learned attention vector, also of dimension D. The centered dot gives the dot product of a node state and the attention vector. exp exponentiates each score, and Σ adds all such terms for indices j from 1 to n, where n is the number of nodes in the input tree. The denominator normalizes the weight within this tree. The authors initialize a randomly and learn it along with the rest of the encoder.

v = Σ_{i=1}^n αᵢ hᵢ

v is the fixed-width embedding for the entire snippet. Σ sums over the n nodes, i identifies the node, αᵢ is its scalar attention weight, and hᵢ is its state vector. Multiplying a state by its weight scales that node’s contribution to the total. Since the output is a weighted sum of D-dimensional states, the vector has dimension D regardless of the number of nodes.

The attention vector is shared across inputs. Different trees can still emphasize different nodes, because the scores depend on their states and the normalization depends on the other nodes in each tree. The weighting happens before prediction of any individual subtree. All of that snippet’s target scores therefore come from the same pooled vector. This is also the vector that becomes available for clustering or retrieval when the pretraining prediction layer is set aside.

Predict the observed fragments and keep the encoder

Each subtree in the vocabulary has a row in a trainable matrix. To score a candidate, InferCode compares that row with the snippet vector using a dot product. A softmax then turns the candidate scores into a distribution over the vocabulary. The whole-snippet vector and the target vectors are learned together. Across examples, the training signal adjusts the encoder as well as the representation of each target.

q(ℓᵢ) = exp(v · W_subtrees[i]) / Σ_{ℓⱼ ∈ L} exp(v · W_subtrees[j])

L is the set of training subtrees used as the target vocabulary. ℓᵢ is the candidate subtree at index i, and ℓⱼ is the candidate at index j. W_subtrees is the trainable matrix with |L| rows, one for each vocabulary entry, and D columns, one for each embedding coordinate. The brackets select the indexed row. v is the D-dimensional snippet vector, the centered dot gives its dot product with a candidate row, exp exponentiates the resulting score, and Σ adds the scores after exponentiation over all candidates belonging to L. q(ℓᵢ) is the resulting probability for candidate ℓᵢ given the snippet. The normalizer ranges over candidate rows, indexed by j.

There can be many true fragments in the same tree. The objective rewards the log probability of the observed targets against the shared vocabulary. The distribution therefore describes relative scores for the prediction task. It does not independently assign each subtree a yes-or-no probability with its own normalizer. This is the same sense in which a document can contain many words while the document objective uses a vocabulary-wide distribution to score an observed word.

For pretraining, the authors reuse Java-Large, previously used by Code2vec and Code2seq. It contains 4 million Java files from GitHub. They apply SrcML to obtain ASTs, collect the target vocabulary, and train with softmax cross-entropy. Optimization uses Adam with an initial learning rate of 0.001 on an Nvidia Tesla P100 GPU. The supervision comes from the parsed files, independent of whether examples elsewhere have method names or functionality labels available for another task.

Once training is complete, one route is to turn an incoming snippet into a vector and use that vector directly. The downstream algorithm determines how to compare vectors, while the encoder’s weights stay fixed. The other route is to initialize a supervised TBCNN with the learned encoder weights and continue training for the task at hand. In that case the task supplies both its own training labels and its own prediction layer. The paper evaluates the training objective through the usefulness of these outputs and weights after pretraining. Its reported comparisons concern downstream performance.

Experiments and results

The evaluation separates what the pretrained vectors can do as they are from what the pretrained weights can contribute to later training. In clustering, clone detection, and code-to-code search, the task operates on fixed vectors. Benchmark labels are used to judge the results. In code classification and method naming, labeled examples also participate in fitting the downstream predictor. This distinction matters when interpreting the results. Success with fixed vectors shows that useful relationships already exist in the embedding space, while success after fine-tuning shows that the weights can serve as an effective starting point.

Clustering by program functionality

The clustering test asks whether code snippets for the same kind of problem land close enough together to form recognizable groups. OJ provides 52,000 C snippets belonging to 104 classes. The Sorting Algorithm dataset, called SA, has 10 Java sorting classes, with roughly 1000 snippets per algorithm. InferCode produces a vector for each snippet. K-means then groups the vectors using Euclidean distance. The authors set the number of clusters to 104 for OJ and 10 for SA, matching the known class counts. Individual class assignments are kept for scoring the completed clustering.

The metric is the Adjusted Rand Index, or ARI. Its starting point is to compare pairs of examples. A pair is an agreement if its members are together in both the reference assignment and the clustering, or separate in both. This avoids requiring the arbitrary cluster identifiers to match the class names. For example, a cluster can have any identifier and still receive credit if its membership agrees with the reference.

RI = (a + b) / choose(n_samples, 2)

RI is the Rand Index. a counts pairs placed together both by the reference classes and by the clustering, and b counts pairs placed apart in both. n_samples is the number of evaluated examples. choose(n_samples, 2) is the number of unordered pairs that can be formed by choosing 2 examples from that set. The denominator puts the agreed pairs on the scale of all possible pairs.

The adjustment accounts for agreement that can arise by chance. Raw pair agreement can be misleading when many pairs end up in separate groups. Subtracting the expected index for random labeling provides a reference point for interpreting the observed agreement.

ARI = (RI − E[RI]) / (max(RI) − E[RI])

ARI is the Adjusted Rand Index, RI is the observed Rand Index, and E[RI] is its expected value under random labeling. max(RI) is the maximum Rand Index. The numerator subtracts the chance expectation from the observed score, and the denominator scales it by the separation between that expectation and the maximum.

The baseline embeddings include Word2vec, Doc2vec, and a sequential denoising autoencoder, called SAE. The autoencoder learns a representation by reconstructing text after corruption. This group of baselines uses the sequence of code as text. Code2vec and Code2seq supply a comparison with encoders that draw on AST paths. The paper applies the same clustering procedure to the vectors from the different methods, so each result depends on the arrangement of its vectors under the shared setup.

Code clustering on OJ by Adjusted Rand Index

InferCode yields the closest agreement with the reference classes.

Code clustering on OJ by Adjusted Rand IndexWord2vec: 0.28Word2vec0.28Doc2vec: 0.42Doc2vec0.42SAE: 0.41SAE0.41Code2vec: 0.58Code2vec0.58Code2seq: 0.53Code2seq0.53InferCode (this paper): 0.70InferCode (this paper)0.70
The numbers
System or settingARI
Word2vec0.28
Doc2vec0.42
SAE0.41
Code2vec0.58
Code2seq0.53
InferCode (this paper)0.70

InferCode also leads the SA experiment, with an ARI of 0.62. Code2vec reaches 0.51, and the scores for Word2vec, Doc2vec, and SAE are 0.24, 0.29, and 0.31. The authors’ overview describes their clustering advantage over Code2vec as 12% in ARI. The OJ and SA scores give the dataset-level comparisons. OJ is particularly informative for the transfer question because the pretrained encoder learned from Java while the snippets it clusters here are written in C.

The comparison between baseline groups gives context for the paper’s interpretation. AST-path encoders also organize the code better than the text-based embeddings in these tests. That makes the stronger results for InferCode compatible with a broader benefit from access to structure. The benchmark comparison changes both the encoder and its training objective, however. The later comparison of pretraining targets is the closer test of whether using subtrees contributes to that improvement.

Detecting clone pairs by similarity

The clone experiment turns two code snippets into a binary decision. The authors compute cosine similarity, which compares the direction of the two vectors, and classify a pair as a clone when the similarity exceeds 0.8. The pretrained encoder supplies the vectors, and the cutoff supplies the decision rule. The Code2vec comparison uses the same cosine threshold with vectors extracted from that system. Deckard, DLC, and SourcererCC provide additional comparisons with unsupervised clone detectors.

The paper evaluates the rule on Java from BigCloneBench and C from OJClone. According to the description, BigCloneBench contains 6,000,000 true and 260,000 false clone pairs spanning 10 functionalities in material drawn from 25,000 projects. To build OJClone, the authors select 500 programs per problem for the first 15 problems on the OJ. Their procedure yields a candidate collection of 1.8 million clone pairs and 26.2 million non-clone pairs. The evaluation uses randomly selected sets of 50,000 pairs from each category. This gives the OJClone comparison a balanced sample for scoring, in spite of the much larger population of non-clones in the constructed pairs.

Precision is the share of declared clones that are correct. Recall is the share of reference clones the detector finds. F1 combines the two, rewarding a detector for retaining both instead of achieving a high score on one while losing the other. Looking at all three makes a strict detector easier to interpret. A system can return very few false positives and still have little practical coverage if it misses most of the known pairs.

Unsupervised clone detection on BigCloneBench by F1

InferCode gives the best balance of precision and recall by the reported F1 score.

Unsupervised clone detection on BigCloneBench by F1Deckard: 0.03Deckard0.03DLC: 0.01DLC0.01SourcererCC: 0.03SourcererCC0.03Code2vec: 0.60Code2vec0.60InferCode (this paper): 0.75InferCode (this paper)0.75
The numbers
System or settingF1
Deckard0.03
DLC0.01
SourcererCC0.03
Code2vec0.60
InferCode (this paper)0.75

On BigCloneBench, InferCode records precision of 0.90 and recall of 0.56. Code2vec records precision of 0.82 and recall of 0.40. Deckard and DLC have precision of 0.93 and 0.95, respectively, but their recall is 0.02 and 0.01. This accounts for the low F1 scores of those detectors at the reported settings. InferCode’s higher F1 than Code2vec is accompanied by improvements on both of its component measures. The paper’s overview reports a 15% F1 improvement over Code2vec for clone detection, with the BigCloneBench results showing the larger separation between the systems.

The OJClone results are closer at the top. InferCode records precision of 0.61, recall of 0.70, and F1 of 0.64. Code2vec reaches precision of 0.56, recall of 0.69, and F1 of 0.61. SourcererCC produces the highest reported OJClone recall, at 0.74, with precision of 0.07 and F1 of 0.14. Deckard reaches precision of 0.99 with recall of 0.05. InferCode’s lead here is on the combined measure. The individual measures make clear why a ranking by precision or by recall alone would tell a different story.

This test places a stronger demand on the geometry of the vectors than assigning points to clusters with a known cluster count. Each pair must pass the same similarity rule, and a score just below the threshold receives a different decision from a score just above it. The results establish a useful operating point for the benchmark. Because the comparison is against unsupervised methods, it addresses the case where labeled pairs are unavailable for training a detector.

Finding an implementation in another language

In the information retrieval experiment, the query is code. A Java implementation of an algorithm, for example, is used to look for a corresponding implementation in another language. Each query and candidate can be encoded into the same vector space. Search then becomes a nearest-neighbor ranking, meaning that the candidates nearest to the query vector are returned first. SrcML supplies a common set of node types, so code from the different languages can enter the same encoder. The experiment tests whether that shared input representation supports useful retrieval across languages after pretraining on Java alone.

The search collection combines Rosetta Code implementations with other GitHub files. Rosetta Code contributes around 3000 samples across Java, C, C++, and C#. The authors add 5000 random program files per language as distractors. For the Java collection, they describe gathering projects with at least 10 stars. They also filter the GitHub files on tokens from the names of the Rosetta Code algorithms, to reduce the chance of placing alternate implementations in the distractor set. For instance, the filter can remove a candidate file on the basis that it contains a word such as bubble or sort. The resulting search collection contains about 23,000 files.

The authors use the 3000 Rosetta Code files as queries and retrieve the top 10 results. A relevant result is a Rosetta Code implementation of the same algorithm in another language. The scoring setup assumes one relevant result for the query. Mean Reciprocal Rank, or MRR, averages the reciprocal of the relevant result’s rank across queries. An early match contributes more than a late one. This makes the metric appropriate to the benchmark’s question of how quickly a searcher would encounter the known match.

The comparisons include ElasticSearch as a fuzzy text retrieval baseline, Word2vec and Doc2vec as embedding baselines, and CLIR as an approach developed for cross-lingual text retrieval. The paper discusses FaCoY and Aroma as code-search systems designed for the monolingual setting, so the reported cross-language comparison uses the other baselines. This choice makes the benchmark a test of the proposed cross-language use case against alternatives that can be applied to it.

Cross-language search in the Rosetta Code collection, Java column

InferCode ranks the known algorithm matches ahead of the text-based baselines on the reported metric.

Cross-language search in the Rosetta Code collection, Java columnElasticSearch: 0.13ElasticSearch0.13Word2vec: 0.33Word2vec0.33Doc2vec: 0.32Doc2vec0.32CLIR: 0.29CLIR0.29InferCode (this paper): 0.57InferCode (this paper)0.57
The numbers
System or settingMRR
ElasticSearch0.13
Word2vec0.33
Doc2vec0.32
CLIR0.29
InferCode (this paper)0.57

InferCode has the highest MRR in each language column. Its other reported scores are 0.45 for C#, 0.51 for C++, and 0.54 for C. In those columns the strongest baseline differs. Word2vec reaches 0.36 in C#, Doc2vec reaches 0.38 in C++, and CLIR reaches 0.39 in C. ElasticSearch has the lowest MRR in every language column. The paper’s overview describes an average 13% MRR improvement over CLIR across languages. The per-language figures show both the reach of the result and the variation behind the overview. A single baseline score would miss that the competing retrieval approaches trade places.

The search result gives a practical meaning to cross-language transfer. A shared parser vocabulary lets the encoder accept the inputs, but acceptance alone could yield vectors with little useful relationship across languages. On this collection, ranking by those vectors brings the known algorithm matches forward more often than the alternatives do. The evaluation ties that conclusion to the Rosetta Code relevance judgments and the accompanying GitHub distractor collection.

Initializing a classifier with the pretrained weights

The supervised classification experiment returns to OJ. It asks for the functionality class of each snippet, using labeled examples to train the predictor. The split is 70:20:10 in training, testing, and validation order. The authors then vary how much of the training portion is available for fine-tuning. The conditions use 1%, 10%, and 100% of that portion. The test score is classification accuracy, the proportion of cases assigned to their correct class.

This test compares two ways to start the TBCNN. One uses the encoder weights obtained from subtree prediction on Java-Large. The other starts with randomly initialized weights and learns under supervision. The experiment also compares with ASTNN trained from scratch, alongside TextCNN and Bi-LSTM. The paper specifies full labeled training data for the text baselines. Their results provide context for how far the pretrained classifier can get at different amounts of supervision.

With 1% of the labeled OJ training portion, the fine-tuned system reaches 70.4% accuracy. With 10%, it reaches 87.6%, close to the fully supervised TextCNN at 88.7% and Bi-LSTM at 88.0%. With 100%, the pretrained system reaches 98.0% accuracy, compared with 94% for the randomly initialized TBCNN and 97.8% for ASTNN. The paper describes the increase over its randomly initialized TBCNN as 4% in accuracy. It presents the proximity to ASTNN as evidence that pretraining can bring its own encoder to the level of a strong task-specific approach on this setting.

The partial-data figures also show a substantial dependence on labeled data within the pretrained conditions. They report what happens when that initialization is paired with each training fraction. The results table gives one supervised TBCNN score, so the closest matched comparison for evaluating initialization is at the full training fraction. The lower fractions answer a related question about attainable accuracy with a limited share of the training labels.

Predicting a method name from its body

The naming experiment uses Java-Small and its existing training, testing, and validation portions. The input is the method body, with its header excluded. In the naming procedure described for Code2vec, the learned vector for the code predicts a method-name embedding drawn from a lookup table. As in classification, the authors test pretrained initialization with 1%, 10%, and 100% of the labeled training portion. The baselines in the results are the randomly initialized TBCNN, Code2vec, and Code2seq.

The score concerns the components of a name. A reference like computeResult can be split into the components compute and result. The evaluation credits result_compute as a complete match, so an exact match in this metric can differ in order and surface spelling. Predicting only compute has full precision and 50% recall in the paper’s example. Predicting compute_model_result has full recall and 67% precision. F1 rewards recovering the expected components while avoiding extraneous ones. These examples explain why the reported F1 measures agreement on name content rather than exact spelling of the full identifier.

On Java-Small, the fine-tuned TBCNN reaches F1 of 20.31% with 1% of the labeled training portion and 30.54% with 10%. With 100% it reaches 43.33%. The randomly initialized TBCNN reaches 35.67%, Code2vec 18.62%, and Code2seq 43.02% in the paper’s supervised comparison. The authors describe the gain over their randomly initialized TBCNN as 8% and characterize the full-data result as comparable to Code2seq. Here the transfer stays within Java, but it changes what the encoder is trained to predict. Syntax fragments provide the pretraining signal, and the later labels teach the network to select names.

Taken together, the supervised results support the use of the learned weights for tasks with different outputs. The OJ task predicts a known functionality category for C programs. Java-Small asks for the components of a method name. The improvements over random initialization occur under both of those setups, while the results beside ASTNN and Code2seq establish comparable performance on the specific benchmarks.

What the ablations show

Type and text contribute different evidence

The authors vary the information used to initialize nodes and repeat the fixed-vector evaluations after training on Java-Large. One variant uses node types, another uses token information, and the combined system uses both. The comparison changes the view of each node supplied to the encoder while retaining the purpose of the representation and the downstream task settings. It therefore addresses a narrower question than the comparison with other complete systems.

On OJ clustering, type-only initialization yields an ARI of 0.57, token-only initialization gives 0.28, and the combined system reaches 0.70. For BigCloneBench clone detection, the ablation reports precision. The type, token, and combined settings reach 0.45, 0.49, and 0.90, respectively. For the Rosetta Code search evaluation, the MRR scores are 0.18 with types, 0.39 with tokens, and 0.57 with both. Each result compares the same metric within its own task. In particular, the clone figures describe the correctness of the proposed matches, with recall and F1 covered separately in the main benchmark.

The single-source comparison changes direction across tasks. Type information alone is stronger in OJ clustering, while token information alone does better in the reported clone precision and search evaluations. The consistent result is that supplying both improves over either restricted view. The parser’s categories and the spelling of code fragments provide complementary cues under the studied training setup. The ablation concerns the content of the input features. A separate comparison would be needed to attribute the gain to the particular linear fusion architecture.

Predicting subtrees is a stronger training signal in these tests

A second ablation changes the labels for pretraining. The alternatives are predicting tokens from the snippet, using a target analogous to the words in Doc2vec, and predicting method names, using the kind of supervision associated with Code2vec. The subtree variant uses the selected syntax fragments. This comparison concerns what the snippet vector is trained to anticipate. That is a different choice from what information is used to construct the initial node vectors. Tokens can help the encoder read syntax even when tokens are a less effective target by themselves.

For OJ clustering, the ARI is 0.23 with token prediction, 0.58 with name prediction, and 0.70 with subtree prediction. For BigCloneBench precision, the scores in that order are 0.45, 0.81, and 0.90. For retrieval MRR on the Rosetta Code collection they are 0.32, 0.41, and 0.57. Name prediction is the stronger of the two alternatives on each reported measure, and subtree prediction leads all three comparisons.

The authors offer an explanation for the weakness of method names as a general pretraining target. Different method bodies can have similar names. A naming objective can reward both vectors for scoring similar target names highly, even if their implementations differ in ways a clone detector or a clustering procedure should preserve. The paper cites earlier evidence that similar names can accompany different implementations. Its ablation is compatible with that explanation, while the measured result concerns the choice of labels as a whole. The experiment does not assign an observed error rate to misleading names.

The token result also helps distinguish two roles of syntax. In token prediction the encoder can still receive a tree, but it is asked to compress that tree in a way that recovers individual tokens. In subtree prediction it is rewarded for recovering fragments that express how nodes fit together. This changes which regularities in the input are rewarded. The improved downstream scores support using structural targets in the tested setting. They leave open how much of that benefit comes from the chosen root types, the granularity of the targets, or the way the target vocabulary is distributed.

Cluster plots illustrate the measured differences

The paper uses t-SNE to project embeddings from the first 9 OJ classes into a two-dimensional display. Each plotted point is a program vector and its color is determined by its reference class. The authors compare visualizations made from Doc2vec, Code2vec, and InferCode embeddings. InferCode’s projection generally shows clearer boundaries between classes, which is consistent with its higher OJ clustering score. Some same-class points are still far from one another, including examples the authors point out within a single color.

The visualization helps explain the kind of improvement suggested by the aggregate score. A distance-based clustering algorithm benefits when programs from a class gather in regions with fewer nearby programs from other classes. A projection can illustrate that pattern and also bring exceptions into view. Because t-SNE changes the representation for display and the figure covers a subset of the classes, the quantitative evidence for clustering comes from the full OJ ARI comparison. The figure provides a view of selected embeddings and the authors’ interpretation of their separation.

The paper’s architecture includes a second departure from the original TBCNN, the switch from max pooling to attention. The quantitative ablations vary node initialization and pretraining targets. An otherwise matched pooling comparison remains outside those experiments, so the results give direct evidence for the feature and target choices while leaving the contribution of attention unmeasured.

Limitations

Limits the authors state

The authors treat the connection between syntax and behavior as an assumption behind the method. The assumption is plausible when implementations of related functionality share expressions or other small constructs. They also recognize that solutions to the same problem can differ widely in syntax. A large corpus may provide recurring evidence through smaller fragments or related uses of the code. The method’s objective still rewards recognition of syntactic context, and the link to functionality is supported by performance on the downstream tests.

They also distinguish the benefit of pretraining from the choice of encoder. The main comparisons show what the tested TBCNN achieves under the subtree objective and how its weights transfer. Other encoders could be used to create the same kind of snippet vector and trained against the same targets. The paper discusses an AST-path encoder, ASTNN, and graph-based networks as possibilities. Richer graphs could expose other code relationships, while constructing their edges can require task-specific decisions and extra engineering. The authors leave direct comparisons of alternative encoders under the same pretraining scheme to future work.

For clone detection, the reported benchmark is explicitly an unsupervised comparison. The paper discusses supervised approaches such as Oreo, CCD, and ASTNN, which train on labeled examples. The authors propose that their vectors or weights could serve such a detector and that improvements to the encoder, the labels, or the training loss might close some of the performance gap between unsupervised and supervised approaches. The study leaves those evaluations open. It also names bug localization and defect prediction as future applications. The evidence for transfer in this paper covers the tasks it actually measures.

The authors’ claim about flexible inputs is conditional on obtaining a tree. SrcML provides a shared syntax vocabulary for the languages they discuss, including Objective C in the use-case description. The cross-language search evaluation covers Java, C, C++, and C#. This makes the demonstrated transfer narrower than the languages listed as acceptable to the parser. It also ties the portability claim to the representation produced by SrcML. An unsupported language or an input that the parser cannot interpret falls outside that input interface.

Limits visible in the evaluation

The benchmark comparisons establish usefulness for specific definitions of similarity. OJ uses the problem class as its reference for grouping, and the clone sample from OJ is constructed from selected programming problems. Rosetta Code search treats implementations of the same named algorithm as matches. These are meaningful ways to judge representations, but they cover a bounded set of cases. The results cannot by themselves settle how closely two snippets agree on all inputs or which semantic differences matter to a user looking for substitute code. The encoder compares learned patterns, while those stronger questions would need evidence tailored to program behavior.

The cross-language benchmark also depends on how its search collection is constructed. Its keyword filter reduces the chance that a GitHub distractor contains a known algorithm, and the same rule can remove files that happen to use the filtered words for other purposes. An alternative implementation with different wording can survive the filter. Under the benchmark’s relevance judgments, a returned file outside the designated Rosetta Code matches can count against the ranking even if it is relevant in practice. The results are most directly evidence about retrieving the designated matches in this collection, with an assumed relevant result per query and a cutoff at 10.

For clustering, the algorithm receives the known number of classes as its cluster count. The experiment tests whether useful groups can be recovered at that count. Discovering how many groups exist in an unfamiliar corpus is a separate question. For clones, the common cosine cutoff of 0.8 makes the InferCode and Code2vec comparison straightforward at a particular setting. The paper gives the precision and recall there, leaving their behavior across other thresholds open. The balanced OJClone sample also matters for interpreting precision. A deployment with a different mixture of clones and non-clones can produce a different share of correct alerts even if the detector’s underlying behavior is similar.

The fine-tuning results support a full-data comparison with random initialization and give scores for smaller labeled subsets under pretrained initialization. A learning curve for randomly initialized TBCNN at those same fractions would be needed to measure the label savings directly. Likewise, the paper discusses faster training as a motivation for starting with pretrained weights, while the reported supervised results compare predictive scores. Measuring the training-time benefit would require timing the downstream training under matched conditions and accounting for the cost of the initial pretraining.

There are also limits to the architectural explanation. The target ablation compares subtrees with two substantially different kinds of labels. It establishes a preferred option among those tested, with the downstream measures in view. It leaves the relative importance of particular subtree types and the exclusion of entire control-flow statements unresolved. The input ablation demonstrates the value of using both types and tokens, while the paper leaves attention pooling and alternative encoders without matched comparisons. The cluster visualization provides a view of the embeddings for selected OJ classes, with the wider judgment resting on the scores.

Finally, aggregate benchmark results give limited evidence about which individual programs the encoder handles well. The authors’ plot already shows some examples whose same-class neighbors are far away. The main tables report scores at the level of datasets and language columns. They leave open whether performance is concentrated among certain algorithms, construct types, or degrees of syntactic similarity. The strongest claim supported by the experiments is that subtree prediction yields representations with useful transfer across the measured tasks, including some involving languages absent from pretraining.

What came after

The later citing work is a 2024 survey on applications of pretrained systems in software engineering. It cites InferCode within a broader subject than subtree prediction alone. InferCode illustrates the pretraining pattern relevant to that subject. It learns an encoder from supervision derived from source code, then evaluates reuse either by applying its vectors directly or by transferring its weights into supervised training. The citation establishes a connection to that line of software engineering research. The survey’s title and citation establish its scope and relationship to InferCode, while leaving any particular replication, implementation, or extension unspecified. 预训练模型在软件工程领域应用研究进展

Cite

Cite as Nghi D. Q. Bui, Yijun Yu and Lingxiao Jiang. 2020. InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees. arXiv:2012.07023.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.48550/arxiv.2012.07023 · arXiv 2012.07023

@misc{bui2020infercode,
  title = {{InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees}},
  author = {Nghi D. Q. Bui, Yijun Yu and Lingxiao Jiang},
  year = {2020},
  doi = {10.48550/arxiv.2012.07023},
  eprint = {2012.07023},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2012.07023}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bui-2020-infercode-self-supervised-learning-code/