Elamur Research

Neural Code Comprehension: A Learnable Representation of Code Semantics

Paper · 2018 · Tal Ben-Nun, Alice Shoshana Jakobovits and Torsten Hoefler

Summary

A program can perform the same calculation after its variables are renamed, its independent operations are rearranged, or its source is rewritten in another language. A system that learns from the written order of the code can miss those connections. It can also miss a dependency between statements that appear far apart, such as an instruction that computes a value and a much later instruction that uses it. Neural Code Comprehension asks whether a better account of an instruction’s surroundings can help a system learn what that instruction does. The authors use LLVM intermediate representation, the form of a program that sits between its original source and the machine code a compiler ultimately produces.

The authors compile C, C++, OpenCL, and FORTRAN code into LLVM instructions. They construct a contextual flow graph, or XFG, in which data dependencies connect operations that exchange values and execution dependencies provide routes through branches, loops, and calls. They use graph neighborhoods to train inst2vec, a vocabulary of numerical vectors for normalized instructions. The approach adapts a principle from word embeddings: the company an item keeps can provide evidence about its meaning. The authors claim that their study is the first both to learn embeddings for a compiler’s intermediate representation and to measure the quality of a code embedding space using clustering, analogies, and relative-distance tests together.

The authors then keep the vectors fixed as they train the same basic recurrent architecture on separate tasks. On the POJ-104 algorithm classification benchmark, which has 104 classes and was outside the embedding training corpus, inst2vec reaches 94.83% test accuracy. The previous best result reported in the comparison is 94.0% for TBCNN, and the authors report a 13.8% decrease in classification error. On OpenCL device mapping, where each platform’s dataset has 680 programs, the inst2vec variant that also receives literal values reaches 88.09% accuracy on AMD Tahiti 7970 and 86.62% on NVIDIA GTX 970. DeepTune reaches 83.68% and 80.29%, respectively. On thread coarsening, where the system chooses how much work each GPU thread should perform, the dataset has 17 programs. Plain inst2vec beats the hand-engineered baseline on every platform, reaches a speedup of 1.37 on AMD Radeon HD 5900, and beats DeepTune with transfer learning on half the platforms.

Together, the experiments show that instruction vectors learned from a shared compiler representation can be reused across different kinds of program prediction. They also show why the distinction between an instruction’s type and its exact operands matters. Removing constants makes it easier to learn a shared vector, while restoring them can help a predictor choose where a program should run. The authors release the code, datasets, trained embeddings, and results through the NCC repository. Their evidence concerns the relationships recovered by the embedding tests and the decisions measured in the benchmarks.

Deep dive: Neural Code Comprehension: A Learnable Representation of Code Semantics

Neural Code Comprehension learns vectors for LLVM instructions from data and control flow, then tests them on algorithm and performance prediction. · about 35 minutes to read

The problem and its context

A program’s written form is only part of the evidence

Suppose a programmer calculates a value near the beginning of a function and uses it near the end. The instructions between those points may have little to do with that value. A reader interested in how it was computed follows the variable from the use back to its definition. A technique that assigns context according to nearby source tokens starts with a different grouping. To recover the same relationship, it must learn to connect pieces of code that its input puts far apart.

Execution adds another relationship. A condition may determine which block runs even when the instructions in that block consume no value produced by the condition itself. Similarly, a call can shift execution to code elsewhere in a file or to a function whose implementation is outside what the compiler can inspect. Conversely, neighboring source statements can belong to different branches, so they may describe alternatives during execution. The paper takes both value movement and execution structure as evidence about the roles of instructions.

These problems matter when the prediction concerns something larger than a line of code. A classifier needs to recognize an algorithm across implementations that differ in style. A performance predictor needs to recognize operations relevant to the choice of a device even when those operations are expressed through different arrangements of source code. The authors frame such problems as classification or prediction from a program representation. Their motivating observation is that a change in syntax or statement order can preserve the program’s result, while a small change in a constant or operation can matter to performance.

The breadth of available code made the choice of representation consequential. The paper cites GitHub’s report of approximately 1 billion commits in 2017 across 337 programming languages. The figure illustrates why a method defined around the syntax of a particular source language has a restricted starting point. A separate tokenizer is only part of the work involved in crossing that boundary. Languages can package different amounts of computation into what each calls a statement, so the learning system also needs a common unit to compare.

What earlier approaches treated as context

The paper places its work alongside the naturalness hypothesis, which treats software as a medium of human communication and argues that useful regularities can be learned from software corpora. Those regularities make it plausible to adapt statistical methods from natural language processing. The authors credit earlier work with applying learned representations to tasks such as function naming, code summarization, code completion, and algorithm classification. The survey they cite situates these efforts within software engineering. A Survey of Machine Learning for Big Code and Naturalness

One approach builds a vocabulary from source tokens such as keywords and punctuation. It can learn a vector by asking which other tokens tend to appear nearby. The order is easy to obtain, and its regularities can be useful, especially where the desired prediction relates to how people write or name code. The problem identified by the authors is that textual distance has no guaranteed correspondence to dependence. Even a sequential architecture capable of carrying information over long spans must discover which earlier tokens matter to a later operation. The proposed graph makes some of those links available before training.

Other approaches already gave learning systems structural information. An abstract syntax tree organizes a program into nested constructs. It can distinguish, for instance, the parts of an expression from the enclosing statement. Earlier work had used the nodes of such trees, paths between nodes, and extra edges relating uses and updates of variables. The background thus includes rich alternatives to token order. The paper’s particular change is to start with compiler instructions and define their context through a joint account of values and execution. A General Path-Based Representation for Predicting Program Properties · Learning to Represent Programs with Graphs

Compiler research offered its own precedents. The paper points to the Program Dependence Graph and Sea of Nodes as representations in which related operations can be organized through graph structure. It also discusses uses of dependence graphs for statistical program analysis and for deciding the direction of copying between programs. The contribution the authors identify is narrower than introducing dependence graphs to learning. They use a graph that combines data and execution relationships specifically to choose the training neighborhoods of instruction embeddings. The graph can discard distinctions that a compiler would need to retain because its purpose is to supply context rather than serve as executable intermediate code.

Program optimization also had approaches based on search, reinforcement learning, stochastic compilation, and empirical performance tuning. The paper places these beside learned feature extraction. A search for a faster program or a procedure for choosing a configuration addresses an optimization objective directly. The authors ask whether a representation learned before the task is specified can provide useful input to several such decisions. Their discussion of earlier OpenCL work is especially relevant because it had already used learned source-token representations for device mapping and thread coarsening. That work gives the paper comparisons on concrete problems as well as a reason to try a representation that can be shared beyond OpenCL. Stochastic Superoptimization

Similarity in what an instruction does

The paper adapts the distributional hypothesis to code. Its proposal is that instructions found in comparable dependency neighborhoods will frequently behave in comparable ways. This version of distributional semantics is meant to apply to compiler output arising from both human-authored and generated programs. It depends on patterns in computation, even when the conventions of human authorship are weak or absent.

The authors use an operational view of semantics. An instruction can change the state of the program or machine, and it can use resources in the process. Arithmetic instructions may make related kinds of state changes in spite of operating on different types. Other instructions may be related because they use similar resources. This supports a graded notion of resemblance. Two versions of an algorithm that vary in the types they use can retain a common structure while differing in the exact operations performed. The embedding is intended to reflect such relationships, which later tests can probe through neighborhoods and systematic changes between instructions.

The method, step by step

A compiler gives the learning system its units

A program passes through two forms relevant to the method. During embedding training, the authors build graphs and use them to determine which instructions count as neighbors. When a predictor later reads a program, it receives a sequence of vectors for its instructions. The connection between those stages is the vocabulary of normalized LLVM statements. A statement learned from graph neighbors becomes a reusable vector that can appear in sequences from other programs.

From source code to a task prediction

The steps in order.

From source code to a task predictionStep 1: Compile source to LLVM intermediate representation1. Compile source to LLVM intermediate representationStep 2: Connect value dependencies and execution dependencies2. Connect value dependencies and execution dependenciesStep 3: Normalize statements for a shared vocabulary3. Normalize statements for a shared vocabularyStep 4: Extract nearby statement pairs from the graph4. Extract nearby statement pairs from the graphStep 5: Learn instruction vectors from those pairs5. Learn instruction vectors from those pairsStep 6: Look up vectors for a program’s instructions6. Look up vectors for a program’s instructionsStep 7: Train a recurrent predictor with fixed vectors7. Train a recurrent predictor with fixed vectors

LLVM separates language-specific processing from the work of generating code for a target. A compiler frontend translates a source program into an intermediate representation, abbreviated IR. Optimization can operate at that level. A backend can then translate the result to instructions for a particular machine. The authors choose the middle layer because it expresses operations at a more regular granularity than source statements while allowing a common vocabulary across the languages and targets in their study.

The instruction is the unit of the vocabulary. A load, for instance, can specify a result identifier, an operation, the type of the loaded value, and the identifier of the input pointer. It can also carry parameters and metadata. This gives the authors a structured expression to normalize. The final vocabulary can preserve the distinction between a floating-point load and other operations without giving every local variable spelling its own entry.

The authors use Clang and Flang to compile the training sources. The fact that sources converge on LLVM IR does not require them to converge on identical instruction sequences. Compiler choices can affect the resulting statements, and the paper takes advantage of that variation during corpus construction. The common feature is the instruction language in which the resulting programs are expressed.

A property of LLVM IR that the method relies on is static single assignment, or SSA. Each SSA variable receives its value at a single defining statement. A computation written as a source expression can accordingly become several instructions whose temporary results are named, with the final calculation consuming those names. A later use of a name points back to its definition. This provides a direct way to identify the flow of values without requiring the learner to infer it from repeated source-level variable names.

Branches make single assignment more interesting. Suppose either branch of a conditional computes a value and the rest of the program needs the selected result. LLVM can introduce a φ expression at the point where execution paths meet. The symbol φ names a selection associated with the incoming paths. The expression lists which value supplies the result for each predecessor. During a particular execution, the path taken determines which incoming value is used. When the graph is built, the alternatives make it possible to record connections to the definitions in the different blocks.

LLVM organizes instructions into basic blocks, which are regions without an internal split in control flow. Within a block, the inputs and result of an instruction expose the immediate dependencies between values. A block boundary may bring in a different kind of connection. One block can precede another in execution, or a value reaching a join can come from another block. The method uses the distinction between a value identifier and a label identifying a block or function to represent these relationships.

How the contextual flow graph is constructed

The XFG is a directed multigraph. Its nodes represent variable identifiers or labels, including names for basic blocks and functions. Direction records the orientation of a dependency. The graph is a multigraph because the same nodes may be linked by more than one edge. Data-dependence edges carry LLVM statements, while execution-dependence edges provide connections associated with when parts of the program can execute. These roles are important because a graph node in this representation is usually an identifier. The instruction vectors ultimately learned by inst2vec belong to statements.

The authors traverse the IR twice. The initial traversal collects function names and return statements. This supplies information that will be needed when visiting instructions that refer to functions, whose definitions and returns may occur elsewhere in the IR. The next traversal adds graph nodes and edges. Within a basic block, the construction connects the identifiers participating in a data dependency. Between blocks, it records direct connections as well as connections through the relevant label. In the latter case an edge can contribute a route through the graph without carrying a statement itself. Identifiers that lack a dataflow parent are attached to their corresponding label or to the program root.

A branch illustrates why the additional routes matter. Operations in different blocks may have a connection through the conditions under which execution arrives at those blocks. A dataflow view connects a producer and consumer when a value passes between them. The label-based routes also make context available when definitions, uses, and execution relationships cross block boundaries. A φ expression can therefore participate in routes through both the values it selects and the labels that distinguish the incoming paths.

With these rules, the graph can have paths through branches, loops, and function calls, including recursion. A loop introduces the possibility of returning to an earlier block. Recursion can connect a function to a call that eventually invokes the same function. Graph paths provide a finite representation through which those relationships can contribute to neighborhood selection. The procedure uses the compiled program structure available to it, so it does not require an observed execution through the branch or a trace of every loop iteration.

The paper gives the following construction cost.

O(n)

Here n is the number of SSA statements in a program, and O denotes an asymptotic upper bound on the growth of the construction time. The parentheses identify the quantity that determines that growth. The authors report a linear bound for obtaining the XFG, citing the construction of the IR and the passes made over its statements. The bound concerns construction of the graph. Generating the neighborhoods used for learning and fitting the embeddings are further stages.

A function call’s treatment depends on what the compiler can see. If the called implementation is available in the compiled IR, as it can be with static libraries or header-only code, the construction can traverse the available statements. If the implementation comes from dynamically linked code and is absent, the call statement represents the interaction. This makes the difference between seeing a call and seeing its implementation explicit. A call still supplies an instruction to the vocabulary when the statements that implement the callee are unavailable.

The graph is intended to supply associations among instructions. Its construction can tolerate ambiguity about distinctions such as parameter order where recovering all such details would be important for other purposes. In this setting, the practical question is whether two statements should supply context for each other. The authors can choose graph relationships for that question while leaving the source and IR as the representations that carry the original program information.

Turning statements into a finite vocabulary

An unprocessed instruction includes details that can multiply the number of distinct vocabulary entries. A local identifier can have a different name each time a similar calculation appears. The same arithmetic operation can use many immediate values, which are literals written directly in the instruction. If every name and value is part of the vocabulary key, many closely related statements will have few examples of their own.

The authors remove comments and metadata and replace identifiers with a common marker, %ID, in their description of the preprocessing. Immediate values receive markers for their kinds. <INT> represents an integer literal, <FLOAT> a floating-point literal, and <STRING> a string literal. The compilation and graph stages can use the original identifiers to establish dependencies, while the vocabulary can treat the resulting occurrences as instances of a shared normalized statement. The literal values are saved separately for downstream tasks that may need them.

The floating-point addition example in the paper shows the effect. An addition involving 1.3 and one involving 5.2 can share an embedding when the other elements of the normalized instruction agree. Such a vector can represent features of the operation that are common to both cases. The stored immediates make it possible to distinguish the examples later. This separation matters because both the operation and the exact value can be relevant, but they need not be represented by the same vocabulary key.

Normalization also inlines data structures. A type name can identify a structure whose constituents carry the information necessary to recognize a similar layout elsewhere. Encoding the constituents in the instruction preserves that information without depending only on the original name. The subsequent analysis illustrates this with operations on a complex type that LLVM expresses as an aggregate of floating-point values. Type structure is consequently one of the signals still available after the replacement of identifiers and literals.

Learning from graph neighborhoods

The graph used to trace dependencies has identifier nodes and statement-bearing edges. To produce examples for skip-gram training, the authors derive a dual graph whose nodes are statements and omit duplicate edges. They then collect pairs of statements that lie within the selected range of one another. A graph path can connect statements through relationships that are invisible to a window of adjacent source lines.

The paper defines a context of size N to include pairs joined by a path of length at most N. The symbol N is the chosen maximum path length in the statement graph. Increasing it allows more distant statements to become training partners. The paper considers context sizes of 1, 2, and 3 statements in its analysis and uses 2 for the vectors fed into the task predictors. A larger neighborhood exposes additional relationships, including dependencies connected by intermediate operations. It also increases the range over which a pair may be grouped even when its members have relatively little in common for the purpose of learning a vector.

The training objective comes from skip-gram. Given a statement, the training procedure seeks to predict statements found in its context. The vocabulary entries are distinct normalized statements, and the pairs give examples of which entries occur together. A vector associated with a statement is therefore useful for predicting what tends to surround that statement in the dependence graph. The paper adapts the source of context while retaining the learning idea from word representations. Distributed Representations of Words and Phrases and their Compositionality

The pair construction and filtering determine which patterns the objective can see. Statements occurring less than 300 times in the training dataset are discarded. Pairs whose members are identical are discarded as well, and frequent pairs undergo sub-sampling, which means some of their occurrences are left out of training. The first decision focuses learning on recurring statements. The identical-pair rule gives the objective examples relating different vocabulary entries, and sub-sampling keeps frequently recurring pairs from supplying all their available repetitions.

The authors fit vectors of dimension 200 for 5 epochs. Dimension 200 is the number of coordinates in each learned vector, and the epoch count describes passes through the training data used to fit them. They use Tensorflow, with softmax cross-entropy for the prediction objective. Softmax converts candidate scores into a distribution, and cross-entropy penalizes the learner when it gives a low probability to an observed context statement. Optimization uses Adam with its published default hyper-parameters. Adam: A Method for Stochastic Optimization

Obtaining varied training examples

The authors select corpora representing different domains, including operating systems, scientific computing, computer vision, and machine learning, alongside high-performance computing code and benchmarks. Tensorflow contributes machine-learning source code as well as being the framework used for training. The Linux kernel supplies operating-system code, COSMO supplies scientific code, and OpenCV supplies computer-vision code. This mixture matters to the hypothesis because related instructions can occur in programs written for very different purposes.

The combined corpus statistics report 24,030 files and 50,450,789 LLVM IR lines. The table gives a combined vocabulary size of 8,565 and lists 640,926,292 XFG statement pairs. These quantities describe different objects. The files produce IR lines, recurrent normalized statements supply the vocabulary, and graph neighborhoods supply the pairs. The raw count of lines therefore does not measure vocabulary size, and the reported pair count should be read alongside the filtering and sub-sampling applied for training.

The corpus includes both existing and procedurally generated code. For the generated portion, the authors use C and the Eigen C++ library. They vary the operations, dimensions, and types in templates for linear algebra programs. This gives the training process instruction uses arising from changes that can be controlled at the source. The combined corpus table attributes 17,801 files and 26,045,547 LLVM IR lines to the synthetic portion. These figures make the generated examples a substantial part of the training setup.

The authors compile for Intel CPUs and for NVIDIA and AMD GPUs. They use a project’s compilation flags when those are available and also choose optimization and target architecture flags at random. The resulting corpus mixes differences in what programmers wrote, differences introduced by template generation, and differences that arise from compilation choices. The vocabulary and graph contexts are therefore learned over the IR actually generated under this procedure. A statement’s vector can reflect recurring relationships across these conditions without requiring the compiled output to be identical.

From an instruction vector to a program prediction

The downstream network receives a program as a sequence of LLVM statements. It looks up the corresponding vector for each normalized instruction. Statements missing from the vocabulary receive the vector of a designated unknown entry. During supervised training, the lookup matrix stays fixed. The task labels can guide the later layers in how to use the vectors, while the vectors themselves continue to reflect their earlier graph-context training.

The sequence passes through stacked long short-term memory layers, or LSTMs. An LSTM is a recurrent component that updates a state as it reads successive items. In the authors’ architecture the two stacked layers have 200 units each, and the sequence is reduced to a fixed-length program representation. This is where the method combines dependency-based pretraining with sequential program input. The graph influenced which information was represented by the lookup vectors. The recurrent layers process the order in which those vectors occur in the program supplied for prediction.

Optional auxiliary inputs can be attached to the program representation before the following layers. For instance, the device-mapping task supplies information about the input and the work-group size. After batch normalization, a dense layer with 32 units and rectified linear activations further transforms the representation. The output has a unit for each possible class. The architecture description reports sigmoid activations and selects the class with the largest output. The training description gives categorical cross-entropy as the supervised loss and Adam as the optimizer. These details belong to the task training, separate from the softmax cross-entropy used to learn statement vectors.

The authors also test ways to return immediate values to the predictors. In the direct concatenation variant, each instruction reaches the first recurrent layer with its embedding and its corresponding immediate values joined together. The recurrent layer can process the literal in association with the operation that used it. The width of the input to that layer is the embedding dimension plus the length of the list of immediates.

A second variant starts by joining the same information but sends the result through a fully connected layer before the recurrent layers. That projection returns the combined input to the width of the original instruction vector. The third variant processes the sequence of immediates through a separate LSTM. The output of this additional branch is added to the program-level representation as auxiliary information. In that arrangement, the immediate values contribute a representation of their own sequence, without being joined directly to the vectors of their source instructions.

All of these variations preserve the stored inst2vec vectors. They differ in where a task’s trainable layers first see the numeric information that was abstracted out of the vocabulary. The experimental comparison therefore addresses both the presence of immediate values and the way the predictor receives them.

Experiments and results

Testing the representation and its use

The authors evaluate the method at the instruction level and at the program level. Instruction-level tests ask whether nearby vectors correspond to related instructions and whether a transformation between instructions is reflected in a repeatable displacement. Program-level tests ask whether a predictor can use the sequence of fixed vectors to choose a label or a performance setting. The distinction matters because a good result on one task can depend on details of the task architecture or labels. Direct tests of vector geometry provide evidence about relationships in the shared representation before the downstream architecture uses it.

For the clustering analysis, the authors visualize the vectors with t-SNE, which projects the learned space into a form that can be plotted. The colors come from instruction and type categories. They include such groupings as operations involving pointers, floating-point values, and aggregate structures. A group in the plot helps the reader see whether vectors associated with a category gather together. The authors combine these visual comparisons with quantitative tests in the original space.

For analogy testing the authors generate questions using LLVM syntax and instructions found in the vocabulary. A question supplies a pair of related instructions, gives another instruction, and asks for the comparable counterpart. For example, the transformation that takes integer addition to floating-point addition suggests a corresponding transformation for subtraction. A structure analogy asks how an extraction from an aggregate corresponds to extraction from a vector, then tests the analogous change for another element position.

The paper describes its analogy query using the following expression.

a − b + c

Here a, b, and c denote the vectors for the instructions supplied in the analogy. The minus sign indicates vector subtraction and the plus sign indicates vector addition. In the paper’s stated expression, the difference of the first vectors is combined with the remaining vector to obtain a point for the neighbor search. The expected instruction counts as recovered if it is among the top-5 neighbors by cosine distance, a measure based on the directions of the vectors.

The distance tests are generated from instruction categories in the LLVM reference. They check relative proximity through the following form.

d(a, b) < d(a, c)

Here a is the reference statement and b and c are the comparison statements, each represented by its learned vector when computing distance. The function d gives a distance between the entries inside the parentheses, with the comma separating its arguments. The sign < asks whether the left-hand distance is smaller. The tests use this ordering to ask whether instructions expected to use similar resources lie closer than the corresponding comparison instructions. An analogy score counts successful retrievals for a specified transformation family, while a distance score counts successes on relative comparisons.

Algorithm classification on POJ-104

The classification task uses code collected by a Pedagogical Open Judge system. POJ-104 has 104 program classes and draws on submissions by 500 different people, with a randomly selected subset of contributors per class. The task is to assign an implementation to its class from the code supplied to the predictor. Multiple authors can express the same algorithm differently, so classification requires the system to find patterns that recur across implementations.

The authors follow the earlier experiment’s 3:1:1 split for training, validation, and testing, in that order. They prepend include statements so the source files compile successfully. To augment training, they compile each training file 8 times with different flags, varying optimization and fast-math settings. This creates alternative compiled views of programs whose class labels remain the same. The augmentation described in the paper is applied to the training portion. The supervised inst2vec classifier is trained for 100 epochs, while the embeddings it looks up remain fixed.

The comparison includes a surface-feature approach that combines a bag-of-trees representation with a support vector machine, a 600-cell recurrent baseline, and TBCNN. The latter works with abstract syntax tree nodes and uses tree convolution and dynamic pooling to summarize their structure. The inst2vec results are measured against the previously reported baseline numbers. The comparison therefore puts a pretrained instruction vocabulary and recurrent reader alongside approaches built around the source and its syntax.

POJ-104 algorithm classification test accuracy

The classifier using fixed inst2vec embeddings has the highest test accuracy in the comparison.

POJ-104 algorithm classification test accuracySurface Features: 88.2Surface Features88.2RNN: 84.8RNN84.8TBCNN: 94.0TBCNN94.0inst2vec (this paper): 94.83inst2vec (this paper)94.83
The numbers
System or settingaccuracy %
Surface Features88.2
RNN84.8
TBCNN94.0
inst2vec (this paper)94.83

The inst2vec classifier reaches 94.83% test accuracy, compared with 94.0% for TBCNN. The paper expresses this improvement as a 13.8% reduction in classification error and reports a new best result on the benchmark. The surface-feature baseline reaches 88.2% and the earlier recurrent baseline reaches 84.8%. The paper’s embedding corpus does not include POJ-104, so the vectors used for this result were learned on other code. The predictor itself learns from the POJ-104 training split, including the augmented versions of its programs.

The result shows how transfer works in this experiment. Individual LLVM statements arrive with vectors already shaped by contexts from a different corpus. The trainable recurrent layers learn how their combinations relate to the program classes. A test success is a correct class assignment for a program in the benchmark’s test split. It need not involve matching an entire held-out program to a counterpart in the embedding corpus, which was gathered for instruction-level training.

Choosing between a CPU and a GPU

The device-mapping task asks which device will run an OpenCL program faster for the supplied configuration. The comparison uses an Intel Core i7-3820 CPU and, in separate settings, either an AMD Tahiti 7970 or an NVIDIA GTX 970 GPU. The prediction uses the code, the input data size, and the work-group size, which describes how many threads cooperate in a group with shared memory. The additional inputs let the predictor respond to differences in the work a program will perform for a particular case. GPU & parallel computing

The authors use the OpenCL dataset and experimental methodology of Cummins and colleagues. The dataset has 680 programs for each platform. The comparison includes a hand-engineered feature method by Grewe and colleagues and DeepTune, the earlier learned approach. Neural Code Comprehension replaces DeepTune’s specialized OpenCL source processing and token embeddings with its own LLVM-based representation. The authors use stratified 10-fold cross-validation, which retains class proportions across the folds. They run training 10 times, randomly initializing the trainable weights for each run, and report the best outcome.

The paper reports prediction accuracy and realized speedup. Accuracy counts whether the selected device is the faster one. Speedup measures the performance of following the selections relative to a static mapping. That static mapping picks the device that performs best on average for the platform comparison. The speedup reference is the CPU for AMD Tahiti 7970 versus the Intel CPU and the GPU for NVIDIA GTX 970 versus the Intel CPU. This matters because the classification and speedup numbers answer different questions. One counts correct choices, and the other depends on the runtime consequences of those choices.

OpenCL CPU versus AMD Tahiti 7970 GPU prediction accuracy

Adding immediate values directly to instruction vectors gives the highest device-selection accuracy in this comparison.

OpenCL CPU versus AMD Tahiti 7970 GPU prediction accuracyAlways GPU: 41.18Always GPU41.18Grewe et al.: 73.38Grewe et al.73.38DeepTune: 83.68DeepTune83.68inst2vec: 82.79inst2vec82.79inst2vec-imm (this paper): 88.09inst2vec-imm (this paper)88.09
The numbers
System or settingaccuracy %
Always GPU41.18
Grewe et al.73.38
DeepTune83.68
inst2vec82.79
inst2vec-imm (this paper)88.09

On the AMD comparison, the plain representation reaches 82.79% accuracy. DeepTune reaches 83.68%, and inst2vec-imm reaches 88.09%. The corresponding speedups for these approaches are 3.42, 3.34, and 3.47, relative to the static CPU mapping. Grewe and colleagues reach 73.38% accuracy and a speedup of 2.91. The always-GPU policy has 41.18% accuracy and a speedup of 3.26. Thus a policy can have a lower rate of correct predictions while yielding a higher reported speedup than another policy. The devices’ runtime differences on the cases selected help determine the latter metric.

On the NVIDIA comparison, always choosing the GPU gives 56.91% accuracy and a speedup of 1.00 relative to that same static GPU mapping. Grewe and colleagues obtain 72.94% accuracy and a speedup of 1.26. DeepTune obtains 80.29% and a speedup of 1.41. Plain inst2vec reaches 82.06% and a speedup of 1.42, and inst2vec-imm reaches 86.62% and a speedup of 1.44. The immediate-value variant leads on both measured quantities for each device comparison. In this task, the reported inst2vec-imm results come from the direct concatenation of immediates with their instruction embeddings.

The authors suggest that DeepTune benefits from learning its embeddings along with the device-mapping task. An embedding tuned in that way can respond directly to the task labels. The inst2vec results show that the fixed representation can compete under the reported setup, and the immediate-value comparison shows how it can be improved while its embedding matrix remains fixed. The benchmark includes both the extra runtime-related inputs and the code representation. Its accuracy therefore measures the decision made from that combined input.

Choosing a thread coarsening factor

Thread coarsening changes the amount of work performed by each GPU thread. The prediction task asks which coarsening setting will run a particular OpenCL program fastest on a given platform. The candidate factors are 1, 2, 4, 8, 16, and 32. Factor 1 provides the reference for the reported speedups. The dataset includes 17 programs and evaluates 6 factors for each platform. The reported metric is the speedup achieved by using the predicted setting relative to the reference setting, so the practical effect of a choice is visible even when the winning factor itself is not reported.

The baselines are the hand-engineered features of Magni and colleagues, DeepTune, and DeepTune-TL. The last takes advantage of transfer learning from DeepTune’s device-mapping task. The paper also compares plain inst2vec with an immediate-value variant. In the coarsening results the selected immediate-value method uses a separate recurrent branch for the constants, unlike the direct concatenation variant used for the headline device-mapping results.

On AMD Radeon HD 5900, plain inst2vec reaches a speedup of 1.37, the strongest value for that platform in the comparison. Inst2vec-imm reaches 1.28, while the hand-engineered baseline reaches 1.21 and DeepTune-TL reaches 1.17. DeepTune reaches 1.10. On AMD Tahiti 7970, the corresponding results for plain inst2vec and inst2vec-imm are 1.10 and 1.18. DeepTune-TL leads there with 1.23, while DeepTune reaches 1.05 and the feature baseline reaches 1.01.

On NVIDIA GTX 480, plain inst2vec reaches 1.07 and inst2vec-imm reaches 1.11. DeepTune-TL leads with 1.14, DeepTune reaches 1.10, and the manual features give 0.86. On NVIDIA Tesla K20c, plain inst2vec leads with 1.06. Inst2vec-imm reaches 1.00, DeepTune reaches 0.99, DeepTune-TL reaches 0.93, and the manual features give 0.94. Values below the factor-1 reference indicate that using the predicted settings yields a slowdown relative to the baseline on the reported metric.

Plain inst2vec exceeds the hand-engineered feature method on every platform in the coarsening comparison. Its comparison with DeepTune-TL is divided by platform, as is the effect of providing immediate values. The results give evidence that fixed instruction embeddings can be useful on this task, especially in comparison with the manual feature approach. They also show that the largest speedup on a given hardware platform can depend on the source of transfer or on whether the predictor receives the extra information.

What the ablations show

Dependency types and neighborhood size

The direct representation comparison trains instruction vectors with contexts derived from a control-flow graph, a data-flow graph, or the combined contextual flow graph. The control-flow graph, abbreviated CFG, supplies execution relationships. The data-flow graph, abbreviated DFG, supplies relationships arising from the transfer of values. The XFG combines them. The paper varies neighborhood size for each of these choices, then examines instruction analogies and distance tests.

Semantic distance test accuracy by graph and context size

The combined data and execution neighborhood attains its strongest distance-test result at the middle context size.

Semantic distance test accuracy by graph and context sizeCFG size 1: 51.59CFG size 151.59CFG size 2: 50.47CFG size 250.47CFG size 3: 53.79CFG size 353.79DFG size 1: 56.79DFG size 156.79DFG size 2: 57.44DFG size 257.44DFG size 3: 60.38DFG size 360.38XFG size 1: 60.98XFG size 160.98XFG size 2 (this paper): 79.12XFG size 2 (this paper)79.12XFG size 3: 62.56XFG size 362.56
The numbers
System or settingaccuracy %
CFG size 151.59
CFG size 250.47
CFG size 353.79
DFG size 156.79
DFG size 257.44
DFG size 360.38
XFG size 160.98
XFG size 2 (this paper)79.12
XFG size 362.56

At context size 2, the combined graph reaches 79.12% on the semantic distance test. The CFG at the same size reaches 50.47%, and the DFG reaches 57.44%. The size-1 and size-3 XFG settings reach 60.98% and 62.56%, respectively. The results support the authors’ choice for the pretrained space that they use in the tasks. They also show an interaction between the size of a neighborhood and the relations available to it. Under the data-only graph, the distance score rises across the tested sizes. Under the combined graph, the middle size gives the highest reported score.

The analogy families reveal which relationships become easier to recover. At XFG context size 2, the paper reports 226 successes, or 40.36%, for type analogies and 45 successes, or 84.91%, for options such as fast math. It reports 134 successes, or 8.89%, for conversions and 7 successes, or 87.50%, for data structures. These are the results for their respective question families, measured by the top-5 criterion. Conversion analogies remain difficult even in the authors’ selected configuration. Recovery of analogy targets is consequently much stronger for some kinds of changes than for others.

Data-structure analogies offer a specific qualification. XFG sizes 2 and 3 both reach 87.50% in that category. The evidence for choosing size 2 comes from performance across the tests together, including the distance test and the other analogy families. It does not require the selected context to improve every individual metric. At size 2, DFG obtains 37.50% on structure analogies, while CFG obtains 0%. The combined neighborhood therefore adds evidence that helps on that family as well as on the distance tests, even though enlarging the combined neighborhood from size 2 to size 3 leaves the structure result unchanged.

The visualizations show a corresponding difference in the arrangement of the vectors. With the smallest and largest tested XFG contexts, the authors describe large groups containing multiple types, together with outliers. The size-2 plot shows more clusters dominated by a particular category. This is evidence about the visible organization of the representation when interpreted alongside the quantitative probes. The projection is a visualization, while analogy retrieval and the distance tests are defined using distances in the learned space.

One nearest-neighbor example connects the visualization to the contents of an instruction. The top-5 neighbors of operations on std::complex<float> include operations on the vector form 2 x float. LLVM expresses the complex type as {float, float}. In this example, a vector and an aggregate represented through the same floating-point constituents occur near one another even though their type forms differ. The normalization step preserves those forms within statements, and the training neighborhoods provide usage information that can draw related operations together. The paper presents this as an example of related treatment across data structures.

The comparison answers a question about pretraining contexts. The task experiments use the XFG vectors learned with the selected size. They do not give a parallel table in which a task predictor is retrained with every CFG, DFG, and XFG setting. The intrinsic results therefore establish that the combined neighborhoods perform better on many of the paper’s vector tests. How much of each downstream result can be attributed to a specific graph edge type remains a separate question.

The placement of immediate values

The immediate-value experiments compare four ways to supply information to the downstream predictor. One ignores the saved literals. The others add them directly to each instruction vector, combine them through a learned projection before the recurrent layers, or send the sequence of literals through a separate recurrent branch. This comparison isolates a practical design choice after vocabulary training. All variants can start with fixed embeddings for the normalized instructions, while their supervised input paths differ.

In device mapping, direct concatenation is the strongest of the tested ways to include literals. It takes accuracy from 82.79% to 88.09% on the AMD comparison and from 82.06% to 86.62% on the NVIDIA comparison. The reported speedups also rise, from 3.42 to 3.47 on AMD and from 1.42 to 1.44 on NVIDIA. Joining an immediate to its own instruction at the input preserves their association when the recurrent layers begin processing the program.

The choice of mechanism matters. On AMD, separately encoding the literals gives 76.18% accuracy and a speedup of 3.36. The projection variant gives 72.06% accuracy and a speedup of 2.76. On NVIDIA, those variants yield 79.71% and 72.50% accuracy, with speedups of 1.40 and 1.32, respectively. Each of those accuracies is below that of plain inst2vec on the corresponding comparison. The gain of inst2vec-imm in the headline device-mapping experiment is therefore a result for a particular arrangement of the features. Simply providing a path for literals does not explain the improvement on its own.

The pattern changes on thread coarsening. The direct concatenation variant gives smaller speedups than plain inst2vec on all the coarsening platforms. The separate recurrent branch improves on plain inst2vec on AMD Tahiti 7970 and NVIDIA GTX 480, where it reaches 1.18 and 1.11, respectively. On AMD Radeon HD 5900 and NVIDIA Tesla K20c, it reaches 1.28 and 1.00, below the corresponding plain inst2vec results. The projected concatenation variant also gives smaller speedups than plain inst2vec across the platforms. These comparisons explain why the two headline uses of the name inst2vec-imm refer to different choices of input path.

The authors suggest that the small amount of training data for coarsening contributes to the inconsistent results with immediates. The comparison establishes that their benefit depends on task, platform, and where the features enter the predictor. The experiment does not vary the amount of coarsening data while holding the architecture constant, so the dataset-size explanation remains a proposed cause. The clearest measured effect is the improvement in device mapping when a literal is added directly to the embedding for its own instruction.

Limitations

Limits identified by the authors

The authors make deliberate compromises in constructing a vocabulary. Replacing an immediate value by its kind helps avoid a vocabulary populated by many rare variants of the same operation. The paper points out that concrete values can still be essential to program meaning or performance. Array sizes and iteration bounds are examples. A normalized statement identifies an operation pattern at a useful level of abstraction, while a prediction that depends on a particular size may need the separately retained value. The mixed results from reinserting those values show that representing them effectively is an additional problem.

The paper also identifies a visibility boundary around external code. The XFG can include library statements that are available in LLVM IR during compilation. In the dynamic case it represents the external interaction with a call statement. Accordingly, there are programs for which the dependence neighborhoods are derived from an incomplete view of the operations that will actually execute. The method can still represent the caller and the call, but conclusions about internal library computation require an accessible implementation.

The authors report that plain inst2vec surpasses DeepTune-TL on half the coarsening platforms and that inst2vec-imm does not consistently improve plain inst2vec there. They give the small dataset as a possible explanation and also suggest that DeepTune’s task-specific embedding training may help that approach. Both factors are plausible within their setup. Neither is confirmed through an experiment that varies dataset size or isolates embedding specialization under otherwise identical coarsening conditions.

Finally, the authors identify finer-grained, part-based representations and neural interpretation of programs as directions for future work. The method they evaluate learns entries for whole normalized LLVM statements, with a common unknown entry for instructions absent from the vocabulary. Predictions made with those entries demonstrate useful representation for the chosen tasks. Execution of arbitrary programs is a separate research direction in the conclusion.

Limits visible in the experimental setup

Language independence has a concrete scope in this work. The corpus gives evidence that C, C++, OpenCL, and FORTRAN code can contribute to a common LLVM instruction vocabulary when compiled with the chosen frontends. The paper names additional languages supported by LLVM, but its evaluation does not contain experiments in which each such language is held out and tested. The shared IR is the mechanism that enables reuse. Compiler coverage, the emitted instructions, and their representation in the vocabulary determine how far that reuse has been tested.

Likewise, the paper puts variation in compiler flags to work as a source of training and augmentation. It does not establish that programs with equivalent behavior always give similar vectors or the same downstream decisions when compiled differently. The graph neighborhood supports relationships across source arrangements, but downstream evaluation begins with a sequence of instruction vectors. A change in compilation can alter the sequence, the instructions available to the lookup, and the context relationships that would be present in its graph. Invariance to such changes would need its own measurement.

The intrinsic diagnostics have a defined set of targets. Analogy questions come from particular types of LLVM instruction transformations, and distance tests use categories from the LLVM reference. These tests measure whether embedding geometry agrees with the chosen comparisons. They do not cover every possible notion of similar effects, identical outputs, or interchangeable resource use. The conversion results are an especially direct reminder that success on one family of transformations is weak evidence about another. The clustering plots illustrate aspects of organization, and their interpretation depends on the accompanying distance and retrieval evidence.

The instruction filtering also affects the scope of the claims. Excluding statements that occur less than 300 times and relying on an unknown entry at prediction time can make rare instruction distinctions unavailable to the downstream learner. The experiments show aggregate performance under that policy. They do not report separate performance for programs that rely heavily on statements outside the vocabulary. The proportion of generated code in the training corpus is another feature of the setup whose effect is hard to separate. The paper gives its size and construction procedure but does not report a matched corpus experiment that removes it.

For POJ-104, the held-out test split and the absence of the benchmark from embedding training are good evidence for transfer of the instruction vectors into that classification setting. The classifier still receives labeled examples from the benchmark, and the benchmark supplies the possible classes. A correct result shows that the predictor can assign a held-out example within that label set. It leaves open how the method would handle an algorithm excluded from those labels or programs containing several distinct algorithms.

For device mapping, the reported accuracies are the best results from repeated random initializations under the paper’s cross-validation procedure. The reported scores do not give the distribution of performance across those repeats. The hardware is also part of the target being predicted. The favorable device for a fixed program and configuration is defined by each measured CPU–GPU comparison. The results do not measure transfer to an untested device. For coarsening, the range of measured factors and the small program collection define the available decisions and the evidence for each platform.

Across the task experiments, the comparisons combine several changes in representation, architecture, and input preparation. The authors show that a fixed inst2vec lookup can serve several predictors built around the same recurrent architecture. The graph-context comparison gives direct evidence about the vector space, and the immediate-value tests give direct evidence about the way constants enter these predictors. The remaining benefits cannot all be assigned individually to graph construction, compiler normalization, the diversity of the training corpus, or supervised augmentation from the headline results alone.

What came after

CodeNet, published in 2021, cites Neural Code Comprehension. Its focus is a large-scale code dataset intended to support learning across a diversity of coding tasks. The connection is clearest at the level of the research problem. Neural Code Comprehension asks whether a shared representation learned from code can serve different downstream decisions. CodeNet addresses the data needed to study learning across coding tasks. In the earlier paper, constructing a diverse corpus is part of training the instruction vocabulary, and labeled task datasets serve separate roles in evaluation.

The citation places the LLVM-based representation work in the background of that later dataset effort. CodeNet’s documented contribution here is the dataset and its broad task scope. The citation alone does not establish that CodeNet adopts XFGs, initializes predictors with inst2vec, or repeats the device-mapping and coarsening experiments. The relationship is therefore a continuation of the question of how to support learning across code tasks, with the later work contributing data infrastructure and the earlier work contributing a way to learn from dependency context.

Cite

Cite as Tal Ben-Nun, Alice Shoshana Jakobovits and Torsten Hoefler. 2018. Neural Code Comprehension: A Learnable Representation of Code Semantics. arXiv:1806.07336.

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

@misc{bennun2018neural,
  title = {{Neural Code Comprehension: A Learnable Representation of Code Semantics}},
  author = {Tal Ben-Nun, Alice Shoshana Jakobovits and Torsten Hoefler},
  year = {2018},
  doi = {10.48550/arxiv.1806.07336},
  eprint = {1806.07336},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.1806.07336}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/ben-2018-nun-neural-code-comprehension-learnable-representation/