Elamur Research

NeuroVectorizer: end-to-end vectorization with deep reinforcement learning

Paper · 2020 · Ameer Haj-Ali, Nesreen K. Ahmed, Ted Willke et al.

Summary

A compiler can translate a loop correctly while still choosing a slow way to execute it. On processors with vector instructions, several operations can run together, but the compiler must decide how much work to combine and how to arrange it. Those decisions depend on the loop’s calculations, memory accesses, dependencies, and surrounding structure. NeuroVectorizer investigates whether a system trained through execution feedback can make better choices than the fixed heuristics used by LLVM. Its subject belongs to code and programming languages, but its broader question concerns optimization: when evaluating a decision is expensive, can experience replace repeated exhaustive search?

The framework reads source code, extracts loops, and converts their structure into numerical representations using code2vec. A reinforcement-learning agent then selects a vectorization factor and an interleaving factor. These settings control how the compiler groups operations from different iterations and handles interleaved work. NeuroVectorizer inserts compiler pragmas, compiles the program, measures its execution time, and uses the result as feedback. The compiler retains responsibility for deciding whether the requested transformation is legal. The learned component therefore proposes optimization settings within an existing compilation system instead of generating replacement program logic.

Though the paper uses deep reinforcement learning, its evaluated decision process is a contextual bandit: the agent makes a single joint choice for a loop nest and receives a reward. The reward compares execution time against LLVM’s ordinary vectorizer. Training does not require a precomputed optimal setting for every example. This distinguishes the approach from supervised alternatives, whose labels are obtained by compiling and running all candidate configurations. To make repeated experiments practical, the authors generate more than 10,000 synthetic loop examples and later restrict the comparative training setup to 5,000 samples because exhaustive labeling is costly.

Across the main held-out benchmark comparison, reinforcement learning delivers an average speedup of 2.67× over the LLVM baseline and comes within 3% of the exhaustive-search result. A nearest-neighbor method and a decision tree also benefit from the learned code representation, reaching 2.65× and 2.47× respectively. In a training-efficiency comparison, reinforcement learning reaches strong performance after 5,000 compilations, while the supervised fully connected network needs 70,000 compilations to reach the corresponding level. Transfer experiments report average improvements of 3.42× on PolyBench and 1.1× on MiBench, illustrating that whole-program benefit depends on how much of the workload consists of optimizable loops.

The result supports learning optimization choices from measured consequences, but within a specific boundary. The experiments concern a restricted collection of vectorization settings, a particular execution environment, and benchmarks with varying relationships to the generated training loops. They do not establish universal compiler superiority, a portable policy for arbitrary processors, or a completed solution to compiler optimization as a whole. The paper also identifies interpretability as a deployment difficulty. Its practical contribution is a complete path from source structure to measured optimization decisions, together with evidence that this path can reduce the compilation effort needed to learn useful settings.

Interesting ideas

Learn from consequences when optimal labels are expensive. An optimizer may be able to test a proposed action without knowing the best possible action beforehand. NeuroVectorizer exploits that distinction: execution supplies feedback, whereas supervised labeling requires searching the candidate space. The same approach can help with scheduling, configuration selection, and other tasks where an evaluator is available but exhaustive answers are costly. Its value depends on how much useful experience can be extracted from each evaluation.

Keep the established validator in control. The agent selects pragmas, while the compiler checks whether the implied transformation can be carried out. This divides responsibility between a flexible proposal mechanism and a more constrained implementation. Elsewhere, a learned selector could suggest a database plan, a rewrite, or a proof-search strategy while a separate component enforces admissibility. The reusable idea is the boundary: proposal quality affects performance, but proposal authority remains limited.

Represent enough context to explain the decision. The authors find that an entire loop nest is a better input than its innermost body alone. Outer structure can reveal iteration patterns and accesses that the local fragment conceals. This matters whenever a decision is applied locally but its consequences depend on surrounding material. Examples include selecting a rule for a clause, optimizing a subquery, or choosing a processing strategy for part of a document.

Choose coupled settings together. Vectorization and interleaving influence each other, and a joint predictor works better than independently trained agents. The lesson extends to settings whose effects are conditional on one another. A component can appear beneficial under one configuration and harmful under another, so separately optimizing each choice can miss the useful combination.

Use synthetic variation to challenge accidental cues. The generated dataset varies loop behavior and also changes parameter names. Those name changes address a different problem from broader functional coverage: they reduce dependence on superficial details that can influence the representation. This suggests deliberately separating meaningful variation from irrelevant variation when preparing training or diagnostic data. The resulting system should respond to the former and remain stable under the latter.

Count the expensive operations. The comparison with supervised learning measures training effort through compilations, because compiling and executing candidates is the costly interaction. Counting examples alone would conceal the work required to produce optimal labels. In other settings, the corresponding unit might be a solver invocation, a database execution, or a human review. A fair efficiency comparison includes the cost of obtaining supervision.

Evaluate local gains at the whole-system boundary. NeuroVectorizer’s benefit is much smaller on workloads where loops occupy a limited share of execution. A successful local optimization therefore needs a second evaluation inside the complete workload. This applies to faster parsers, more efficient retrieval stages, and cheaper numerical routines: the surrounding system determines how much their improvement matters in practice.

Deep dive: NeuroVectorizer: end-to-end vectorization with deep reinforcement learning

NeuroVectorizer learns loop vectorization choices from measured runtime, improving LLVM performance while reducing the search needed for training. · about 36 minutes to read

How Mova uses it

Mova is a small language system written in Rust, with explicit linguistic rules, statistical components, structured knowledge, and bounded operational tools. The connections below concern proposed transfers from NeuroVectorizer, not evidence that its reinforcement-learning vectorizer has been implemented in Mova. The status marks describe overlap with documented mechanisms. They are proposals about applicability; they do not report measured effects of adopting this paper.

Idea: Learn from measured consequences without requiring optimal labels. Where: Sections 2.3 and 3.2. Area: optimization and evaluation. Mova: частково є (held-out experiments and experiment journals in world selfplay and docs/training.md). Mova already evaluates proposed changes instead of assuming that a plausible rule is useful. NeuroVectorizer suggests extending that discipline to bounded operational settings whose best values are unknown. A transparent statistical selector could learn from measured runs without first enumerating every alternative. Why Mova: expensive experiments could teach a configuration selector while keeping both the available actions and the acceptance criteria explicit.

Idea: Let a constrained component authorize a flexible proposal. Where: Section 3, especially the discussion of compiler pragmas. Area: execution safety and validation. Mova: вже є (configured capabilities in docs/hybrid-system.md, annotation gates in treeagree, and staging gates in tools/enrich). Mova’s existing boundaries distinguish proposals from admitted actions or knowledge. The compiler arrangement supplies a useful engineering analogy: a selector recommends, and the receiving component checks admissibility. Why Mova: a better selector should improve efficiency without acquiring authority to bypass source, structural, or admission requirements.

Idea: Include the context that determines a local choice. Where: Section 3.2, comparison of loop-nest input with innermost-loop input. Area: syntax and representation. Mova: частково є (en trees, prag frames, and document worlds in world). A rule applied to a token or frame may depend on a containing clause, reported speech, or a preceding event. Mova could compare selectors that receive a local structure with selectors that also receive bounded surrounding structure. Why Mova: this could identify failures caused by missing context rather than encourage increasingly complicated local exceptions.

Idea: Select dependent parameters jointly. Where: Section 3.2, joint prediction of vectorization and interleaving. Area: statistical configuration. Mova: нове. A possible experiment would examine interacting settings in a reader or worker, such as retrieval breadth and the budget for checking retrieved evidence. The digest does not establish a joint selection mechanism for such pairs, so this novelty mark remains provisional. Why Mova: a configuration that is useful only alongside another setting can be missed when each parameter is tuned in isolation.

Idea: Generate irrelevant variation deliberately. Where: Section 3.3, parameter-name changes in synthetic loops. Area: data and robustness. Mova: частково є (contrast sets, negative controls, and deterministic comparisons described in the assessment and training mechanisms). Mova could add meaning-preserving changes of names or other incidental surface details to targeted diagnostics. These would need careful construction: replacing a name must preserve reference and grammatical behavior. Why Mova: stable answers across irrelevant changes would provide evidence that a reader follows roles and relations rather than accidental lexical associations.

Idea: Vary the features that genuinely affect behavior. Where: Section 3.3, generated changes to stride, iterations, instructions, and nesting. Area: data design. Mova: частково є (configured linguistic rules and contrast-based evaluations). Separate generators could vary negation, ownership transfer, clause attachment, or evidential status while retaining an explicit expected distinction. This differs from changing irrelevant names: the purpose is to expose sensitivity where the interpretation should change. Why Mova: controlled variation can reveal the boundaries of a rule more clearly than a collection of unrelated examples.

Idea: Measure efficiency through costly interactions. Where: Section 4 and Figure 9. Area: evaluation and resource accounting. Mova: частково є (tools/jobs records estimated and actual resources, and tools/twin compares predictions with measured runs). For a training or review workflow, Mova could report teacher calls, compilation runs, or evidence checks alongside final quality. The expensive unit would depend on the workflow rather than follow the paper mechanically. Why Mova: this makes a cheaper learning procedure distinguishable from one that merely hides supervision costs outside its reported training loop.

Idea: Evaluate improvements in the complete workload. Where: Section 4.1, MiBench transfer evaluation. Area: system evaluation. Mova: частково є (separate parser, frame, reader, and school assessments). A faster or more accurate intermediate stage should also be tested in the reader or task that consumes it. Existing measurements already show that a targeted reading improvement can leave broad benchmarks unchanged. Why Mova: whole-task evaluation prevents an attractive component result from being presented as evidence of a larger capability gain.

Idea: Express feedback relative to a matched baseline. Where: Equation 2 in Section 3.2. Area: statistics and evaluation. Mova: частково є (paired comparisons and baseline controls in training and assessment). For resource optimization, Mova could compare each candidate against the same task under a reference configuration. This would require a defined metric and a policy for noisy measurements; the paper’s runtime reward should not be copied into linguistic quality scoring without justification. Why Mova: matching the reference to the task helps separate difficult inputs from genuinely poor configuration choices.

Idea: Preserve the direction of a result in the feedback signal. Where: Section 3.2, interpretation of positive reward. Area: evaluation. Mova: частково є (regression gates and journals that retain positive and negative experiments). A configuration log should make it clear whether an outcome improved or harmed the declared objective. That sign should remain separate from the mere success of execution. Why Mova: a worker finishing successfully does not establish that its chosen method was useful, just as successful compilation does not establish faster code.

Idea: Treat excessive resource use as an observed outcome. Where: Section 3.4. Area: bounded execution. Mova: частково є (tools/jobs resource limits and bounded recursive capability calls). NeuroVectorizer makes an overlong compilation influence future choices instead of treating it as missing data. Mova could similarly retain timeout categories when selecting operational strategies. Why Mova: a strategy that repeatedly exhausts its budget should be distinguishable from one that completes with an ordinary negative result.

Idea: Keep timeout penalties separate from measured task quality. Where: Section 3.4 and the PolyBench discussion in Section 4.1. Area: objective design. Mova: частково є (explicit budgets, outcomes, and evidence types in docs/hybrid-system.md). The paper’s timeout rule changes which configurations the agent favors, and its authors later connect that rule to missed performance. Mova could retain both the resource violation and the unavailable quality measurement instead of collapsing them into an unexplained score. Why Mova: this would make the reason for rejecting an expensive strategy inspectable.

Idea: Match the action representation to the available operations. Where: Section 4 and Figure 7. Area: decision procedures. Mova: частково є (typed configured capabilities and explicit rule inventories). NeuroVectorizer’s discrete choices fit the compiler’s supported settings better than rounded continuous outputs. For Mova, a finite registry of admissible operations could be selected directly rather than encoded through an unnecessarily indirect numerical representation. Why Mova: the selector can remain easier to inspect, and unsupported intermediate outputs need not acquire accidental meanings.

Idea: Establish an exhaustive reference on a bounded subset. Where: Sections 2.1 and 4. Area: evaluation. Mova: частково є (finite-relation checks in tools/correspondence and bounded comparisons in the combinatorial tooling). Where a task has a small, explicit option set, Mova could enumerate it to estimate what a selector leaves unrealized. This would be a diagnostic reference, not a claim that enumeration scales to general understanding. Why Mova: it separates failures of selection from limitations of the available candidates.

Idea: Compare a learned selector with random choice. Where: Section 4 and Figure 8. Area: negative controls. Mova: вже є (negative-control requirements in school reports and training principles). Random selection provides a check that an apparent improvement reflects useful input-dependent decisions. For a new worker selector, Mova should define the random control over the same admissible action set. Why Mova: a selector should demonstrate that its observations help, rather than receive credit merely because the candidate set contains good options.

Idea: Reuse a representation with simpler decision methods. Where: Section 4, nearest-neighbor and decision-tree comparisons. Area: representation and transparent statistics. Mova: частково є (shared UD trees, frames, retained graphs, and specialist profiles over shared document structure). Mova could compare a complicated selector with a rule table or a small statistical method operating on the same explicit observations. NeuroVectorizer’s representation is neural; that implementation choice is not required for this transfer. Why Mova: it tests whether useful structure can support a simpler, more inspectable decision mechanism.

Idea: Separate evidence for a representation from evidence for its selector. Where: Section 4, interpretation of the nearest-neighbor and decision-tree results. Area: experimental analysis. Mova: частково є (separate parsing, pragmatic, and reader measurements). If several selectors succeed on the same observations, the observations may be useful independently of the strongest selector. Conversely, changing both at once obscures attribution. Why Mova: clearer attribution helps decide whether to improve the linguistic representation, the downstream reasoning, or the choice procedure.

Idea: Use small executable cases to accelerate experimentation. Where: Sections 3.3 and 4. Area: data processing and experimental design. Mova: частково є (targeted fixed sets, quick assessment tiers, and bounded source packets). Mova can use compact, source-bound diagnostics for rapid experiments, then verify promising changes on broader tasks. The paper’s synthetic loops make execution cheaper but do not remove the need for transfer tests. Why Mova: fast feedback can support more careful exploration while preserving the distinction between a diagnostic success and broad coverage.

Idea: Test whether the training collection covers the decision space. Where: Section 3.3 and Figure 5. Area: dataset analysis. Mova: частково є (dictindex reports source strata, feature support, and absent coverage). A collection may contain many examples yet repeatedly exercise the same useful rule or preferred action. Mova could report which supported actions or linguistic distinctions are represented and which remain absent. Why Mova: coverage information would make dataset size less misleading when rare constructions or senses matter.

Idea: Distinguish average behavior from favorable inference outcomes. Where: Section 4.1, the PolyBench footnote. Area: statistics and reporting. Mova: частково є (deterministic repeated runs and retained run evidence). NeuroVectorizer reports both an average across inferences and a larger best-performance result. Mova should likewise identify whether a result is an ordinary run, a selected run, or a best candidate found through search. Why Mova: the selection procedure changes what a reported success establishes.

Idea: Evaluate transfer across workload families. Where: Section 4.1. Area: generalization. Mova: частково є (multiple reading benchmarks, school subjects, and separate linguistic assessments). A rule or configuration learned from one source family should be tested on another without silently adapting to its assessment answers. The transfer target should be named, and unsupported cases should remain visible. Why Mova: success on variations of a familiar source does not establish usefulness on a structurally different task.

Idea: Treat hardware and execution conditions as part of a configuration’s identity. Where: Section 5. Area: operational provenance. Mova: частково є (CPU reference behavior and separately measured GPU approximants in docs/gpu-exec.md). Performance settings could be recorded with the execution mode and relevant environment instead of treated as universally optimal. NeuroVectorizer proposes architecture features or separate training for different targets. Why Mova: a resource decision learned under one execution path may be inappropriate under another.

Idea: Compare complementary optimization families before composing them. Where: Sections 4 and 5, discussion of Polly. Area: mathematical composition and execution. Mova: частково є (source-bound groupants and explicit compatibility checks; automatic general composition remains direction). Mova could first record where distinct solvers or processing strategies succeed, then investigate a selector or composition under declared assumptions. Why Mova: complementary results suggest a research opportunity, but they do not by themselves establish that the methods can be combined safely or efficiently.

Idea: Change experimental factors separately when diagnosing behavior. Where: Section 4, hyper-parameter experiments. Area: experimental design. Mova: частково є (gated changes, ablations, and experiment journals). Mova’s rule and parameter experiments can preserve a reference configuration and vary a declared factor while holding the rest fixed. This will not discover every interaction, but it makes local explanations more credible. Why Mova: a measured improvement is easier to interpret when the experiment identifies what actually changed.

Idea: Check instability as well as convergence speed. Where: Section 4, batch-size analysis and Figure 6. Area: statistics and optimization. Mova: частково є (repeatability requirements and deterministic native inference). A selector that appears to learn quickly may still yield unstable choices or inconsistent benefits. For statistical training, Mova could examine both quality and stability before admission. Why Mova: reducing training effort is useful only if the resulting behavior remains dependable under the declared evaluation.

Idea: Preserve the difference between a local optimum and broader optimization. Where: Section 4, Polly’s result on benchmark #10. Area: evaluation scope. Mova: частково є (declared domains and conformance profiles for groupants). Exhaustive search is exhaustive only over its stated options. Mova should attach that option set to any claim that a selector is close to optimal. Why Mova: a bounded search result should not conceal a stronger method that operates outside the enumerated family.

Idea: Separate exploration from deployed decision making. Where: Sections 3 and 4, training followed by inference. Area: architecture. Mova: вже є (offline teacher work, separately admitted learning, and teacher-free assessment). NeuroVectorizer provides a performance-optimization example of the same separation: expensive exploration can precede a short deployed decision. Why Mova: experimentation can remain rich without turning assessment or normal execution into an uncontrolled search process.

Idea: Define multiple objectives before optimizing them. Where: Section 3.4 and Section 5. Area: resource policy. Mova: частково є (explicit budgets and prospective cost measurements; a general combined objective is not established). Mova could study tradeoffs among runtime, memory, and retained evidence, but each objective and its priority would need a declared interpretation. The paper discusses such extensions without demonstrating a general solution. Why Mova: an optimizer otherwise risks improving a convenient metric while degrading the property the task actually needs.

The problem and its context

Why vectorization needs a decision procedure

Vector instructions let a processor apply an operation to several data items together. A scalar implementation handles operands individually; a vectorized implementation groups suitable work. Loops are natural candidates because successive iterations frequently repeat the same calculation on different elements. Yet repetition alone does not tell a compiler how to group the work profitably.

NeuroVectorizer concentrates on the vectorization factor, abbreviated VF, and the interleaving factor, abbreviated IF. The paper describes VF as the amount of work packed from different iterations. It associates IF with the arrangement of interleaved accesses and the ability to handle nonconsecutive locations. The important point for understanding the experiments is that the pair controls the generated loop implementation. Neither setting can be judged adequately by assuming that larger always means faster.

The choices depend on several interacting properties. A loop may have a reduction, a conditional assignment, a conversion between data types, or an access pattern with a stride. Nested loops add structure that affects which elements are visited and how calculations relate. Hardware also matters, because the available instructions and supported settings constrain the alternatives.

A manually written setting can exploit knowledge of those details. The authors nevertheless describe manual tuning as costly, prone to mistakes, and inconvenient when code must be maintained or moved to a different target. Their goal is to retain the compiler’s automation while improving the performance decisions that automation makes.

What the motivating example establishes

The paper begins its performance argument with a dot-product-style kernel. It iterates over an integer array, multiplies each element on its own, and accumulates the result. The array contains 512 elements. The authors run the kernel one million times and average execution time to reduce variation.

The reported machine has 16 GB of 2133 MHz LPDDR3 memory and an Intel i7-8559U processor. Its stated frequency is 2.7 GHz, with up to 4.5 GHz, and it supports AVX. These details matter because the experiment demonstrates an opportunity on a concrete execution environment, instead of an architecture-independent ordering of vectorization choices.

LLVM selects VF = 4 and IF = 2 for the baseline. That choice improves performance by 2.6× relative to the unvectorized configuration. The baseline is therefore doing something valuable. NeuroVectorizer’s motivation is not that LLVM fails to vectorize, but that useful headroom remains after its ordinary decision.

In this example, 26 out of 35 candidate factor combinations outperform the baseline. The best reported pair, VF = 64 and IF = 8, produces up to 20% better performance. This shows that choosing a legal and beneficial vectorization does not imply choosing the strongest available configuration.

A second motivating experiment searches the factor combinations for LLVM’s vectorizer tests. The authors report improvements throughout that collection, with the gap reaching up to 1.5× on more complicated cases. These are opportunity measurements: exhaustive search shows that better settings exist. They do not yet show that a learned selector can recognize those settings on unseen code.

Earlier approaches as the paper presents them

The paper contrasts its proposal with LLVM’s existing cost-based decisions. In the authors’ account, those decisions use pre-defined estimates of instruction costs and do not sufficiently represent how operations are organized into a computation. A collection of individually reasonable cost estimates can therefore fail to predict the runtime of the complete transformed loop.

Polly offers a different route. It expresses suitable loops through mathematical structures based on integer polyhedra, making certain transformations easier to analyze. The paper emphasizes tiling and loop fusion as ways to improve data locality. Those transformations can also change the setting in which vectorization occurs.

This distinction becomes important later. Polly is not merely another mechanism for selecting the same VF and IF pair. It can change the loop structure beyond that search space. Comparing it with NeuroVectorizer therefore compares partially overlapping optimization capabilities.

The authors also discuss machine-learning approaches that use manually designed program features, including measures derived from assembly. Their criticism is that such summaries can omit information needed to characterize the code. End-to-end supervised learning addresses feature construction, but introduces another expense: obtaining the desired output for every training example.

NeuroVectorizer combines learned code representations with reinforcement learning to avoid requiring those optimal labels in advance. Its argument is specific. Execution feedback may provide enough information to learn a useful selector without paying for a complete search on every training loop. That claim motivates the later comparison in terms of compilations.

The method, step by step

From a source file to an optimization experiment

The input is a directory containing source programs. A loop extractor identifies loops and retains their context. The representation stage then converts the extracted code into a fixed-size numerical input for the decision agent.

The agent chooses a pair of optimization settings and inserts a pragma at the relevant loop. Clang/LLVM compiles the modified program. Executing the compiled result provides the measurement used to evaluate the choice. During training, that feedback changes the policy used for subsequent decisions.

NeuroVectorizer’s training cycle

The steps in order.

NeuroVectorizer’s training cycleStep 1: Read programs and extract loop context1. Read programs and extract loop contextStep 2: Encode loop structure with code2vec2. Encode loop structure with code2vecStep 3: Select vectorization and interleaving factors3. Select vectorization and interleaving factorsStep 4: Insert pragmas into the source4. Insert pragmas into the sourceStep 5: Compile with Clang and LLVM5. Compile with Clang and LLVMStep 6: Execute and measure runtime6. Execute and measure runtimeStep 7: Update the selection policy7. Update the selection policy

The loop receiving the pragma is the innermost loop when the source contains a nest. The code supplied to the representation stage can be broader: the authors find that including the outermost loop body, and therefore its inner loops, works better than encoding only the innermost body.

This separates the location of the action from the scope of its evidence. The optimization is requested at a particular loop, while the decision receives enough surrounding structure to recognize how that loop participates in a larger calculation.

The authors avoid command-line settings that would impose the same VF and IF throughout the program. Their framework instead makes loop-specific choices. A program can contain different access patterns and calculations, so a globally shared pair would remove part of the flexibility the method is intended to learn.

What code2vec contributes

Code2vec supplies the code representation. Its role is to map a source fragment into a numerical space where fragments with useful similarities can receive related representations. NeuroVectorizer then learns how those representations relate to optimization choices.

The representation has 340 features. These are learned features rather than a manually written inventory of quantities such as instruction counts. Code2vec decomposes the source structure into paths through an abstract syntax tree and learns both path representations and their aggregation into a single vector.

An abstract syntax tree records the structural organization of a program. Instead of treating the loop as an undifferentiated character string, the representation can use relationships among its syntactic elements. The paper’s broader motivation is that structure can carry information about operations and their combinations that a short hand-designed feature list misses.

The attention mechanism belongs to a broader line of work that includes the cited Show, Attend and Tell. NeuroVectorizer uses code2vec as its practical representation component; it does not evaluate that earlier image-captioning system or transfer its reported results into compiler optimization.

The authors describe the representation in terms of semantic similarities and analogies. That language explains their motivation, but it should not be read as a demonstration that the vector preserves every property of a program. The experiments test whether the representation helps select optimization settings, which is a narrower and measurable question.

The learning problem

Reinforcement learning organizes optimization around observations, actions, and rewards. Here, the observation is the code representation. The action is the selected VF and IF. The reward depends on the measured execution time after the compiler processes those settings.

The paper presents the policy objective as follows:

π* = arg max_π E_{τ ∼ π(τ)}[τ]

The symbol π denotes a policy, meaning a rule for selecting actions from observations. The symbol π* denotes the desired policy. The operator arg max identifies the policy that maximizes the stated quantity, and E denotes expectation. The symbol τ denotes a trajectory of states and actions generated under a policy.

The displayed expression is abbreviated: the surrounding explanation identifies expected reward as the quantity being optimized, although the bracketed term is written as the trajectory itself. The methodological point is that the policy should favor decisions with better expected outcomes, not merely reproduce a supplied label.

In the evaluated framework, the agent makes a single decision before the environment returns a result. The paper calls this a contextual-bandit problem. It does not require a long sequence of transformations whose intermediate states must all be evaluated.

The authors use proximal policy optimization, or PPO. Their explanation emphasizes keeping policy updates from departing too abruptly from the previous policy while improving the objective. The paper does not supply the full PPO loss, so understanding NeuroVectorizer does not require reconstructing additional equations for that algorithm.

How runtime becomes reward

The reward compares the candidate’s execution time with the same program under the LLVM baseline:

reward = (t_baseline − t_RL) / t_baseline

Here, t_baseline is the runtime obtained using LLVM’s ordinary optimization decision. The term t_RL is the runtime after inserting the settings chosen by the agent. The reward is their difference normalized by the baseline runtime.

A positive value means that the chosen settings produce a faster program than the baseline. A negative value means that they produce a slower one. Dividing by the reference runtime makes the signal relative to the program being evaluated, rather than allowing long-running programs to dominate simply because their absolute times are larger.

The authors also use the baseline subtraction to give the feedback a clear reference point. The agent is rewarded for improving on an existing compiler decision. It is not being asked to maximize an unexplained score whose relation to useful performance must be inferred afterwards.

This reward measures execution speed. The paper discusses extensions that could include compilation time or generated code size, but those possibilities should remain distinct from the central runtime-based experiment.

Which actions are available

The vectorization choices follow the powers-of-two settings supported in the authors’ LLVM setup:

VF ∈ [2⁰, 2¹, 2², …, MAX_VF]

VF denotes the vectorization factor. MAX_VF denotes the largest vectorization setting supported by the relevant architecture and configuration. The intermediate entries represent the supported powers of two.

Interleaving uses the corresponding form:

IF ∈ [2⁰, 2¹, 2², …, MAX_IF]

IF denotes the interleaving factor, and MAX_IF denotes its supported upper limit. The authors explain that powers of two are a consequence of the compiler interface they use, rather than a requirement imposed by reinforcement learning itself.

The agent predicts the settings jointly. An earlier arrangement used separate agents, but joint prediction performed better. The paper relates this result to the dependence between VF and IF, including their relationship within LLVM’s implementation.

The main implementation uses discrete outputs that identify entries in the available setting arrays. The experiments also try continuous encodings and round them to integer choices. Those alternatives keep the broad optimization goal unchanged while altering how the policy expresses its decision.

Why compiler legality remains separate

NeuroVectorizer inserts hints into source code. It does not directly emit transformed machine instructions. LLVM can reject a requested vectorization when dependencies or predicates make it infeasible.

This is the basis for the authors’ correctness argument. A poor setting can be ignored or can yield disappointing performance, while the compiler continues to enforce its transformation rules. The learned agent does not receive unrestricted permission to rewrite program behavior.

The distinction also affects interpretation of the action. The requested settings and the effective compiled transformation need not always coincide. A policy learns through the resulting runtime, but the compiler may mediate that result by declining an unsupported request.

Building training data that can be executed repeatedly

The authors initially try training with longer programs. Recompiling and executing an entire program for every local setting makes learning slow. They also identify limited availability of suitable open-source benchmarks as a constraint.

Their response is to generate more than 10,000 loop examples from LLVM’s vectorization tests. The generators alter properties including strides, iteration counts, operations, and nesting. They also rename parameters to reduce incidental effects of identifiers on the code representation.

The examples illustrate different demands on vectorization. Some convert values from shorter integer types and write to several arrays. Others fill a multidimensional array, apply a conditional bound, accumulate matrix products, or combine values accessed at alternating positions.

These examples matter because optimization choices should depend on behaviorally relevant differences. An array fill and a reduction may both be loops, but their computation and access structures are different. The training procedure seeks enough variation for the agent to associate those differences with useful settings.

The authors examine optimal settings on the generated collection through exhaustive search. For the distribution shown in Figure 5, MAX_VF = 16 and MAX_IF = 8. The most common optimal pair is VF = 4 and IF = 2, which also matches the baseline’s frequent choice in their experiments. Nevertheless, the distribution contains other optima, motivating an input-dependent selector.

Bounding compilation cost

Some settings cause compilation to take disproportionately long. The framework limits this cost relative to the baseline compilation time. When compilation exceeds ten times that reference, the agent receives a penalty of −9.

The penalty treats an excessive compilation as an undesirable optimization outcome. Without such handling, a small number of difficult experiments could consume much of the available training effort.

The authors report that waiting for these slow compilations did not reveal performance better than all the alternatives they considered. However, the later transfer discussion also identifies the penalty as a possible reason for conservative choices on unfamiliar workloads. The resource rule makes training practical while also shaping what the policy learns.

Experiments and results

Experimental components and comparison setup

The implementation uses code2vec together with an agent built through RLlib. Tune supports the experimental configuration work, and both sit on Ray’s distributed execution infrastructure. The official framework is released as NeuroVectorizer, with support for several decision methods rather than reinforcement learning alone.

The authors first train the representation and reinforcement-learning system. They then perform exhaustive search to obtain optimal-setting labels for the supervised comparisons. Because this labeling requires substantial compilation work, they use 5,000 training samples for the remaining evaluation.

The principal test comparison uses twelve benchmarks described as different from the training examples. These combine tests from LLVM’s suite and include varied control flow, access patterns, data types, and loop structures. The paper mentions unknown bounds and alignment alongside multidimensional accesses and reductions.

The reference is LLVM’s existing vectorizer. Polly provides a comparison with a different optimization family. Additional learned selectors examine whether the representation is useful beyond the reinforcement-learning policy.

Performance on the main benchmark collection

Reinforcement learning achieves an average speedup of 2.67× relative to the LLVM baseline. Its performance is reported as 3% below exhaustive search over the candidate vectorization settings.

The nearest-neighbor method reaches 2.65×, while the decision tree reaches 2.47×. Those results matter because they show that useful performance information is present in the learned representation even when another method makes the final decision.

Main held-out benchmarks, average speedup over LLVM

Reinforcement learning leads these learned selectors, while the shared representation also supports simpler methods.

Main held-out benchmarks, average speedup over LLVMDecision tree: 2.47Decision tree2.47Nearest-neighbor search: 2.65Nearest-neighbor search2.65NeuroVectorizer reinforcement learning (this paper): 2.67NeuroVectorizer reinforcement learning(this paper)2.67
The numbers
System or settingspeedup ×
Decision tree2.47
Nearest-neighbor search2.65
NeuroVectorizer reinforcement learning (this paper)2.67

Random search performs substantially worse than the baseline. This is a useful control: drawing from the available settings does not automatically produce the gains obtained by the learned methods. The agent appears to use regularities in its observations rather than benefit merely from access to a richer candidate set.

Polly improves on the baseline by 17%, while the paper reports it as 56% worse than the reinforcement-learning solution in this comparison. These aggregate results should be read alongside the differences in what the methods can do. Polly can apply transformations outside the VF–IF search space.

That distinction is visible on benchmark #10, where Polly outperforms the exhaustive vectorization search. There is no contradiction. Exhaustive search identifies the best candidate within its enumerated family; Polly can change the loop in ways that family does not include.

The paper’s abstract and conclusion describe an average improvement range of 1.29×–4.73×. The detailed evaluation gives the benchmark-specific aggregates discussed here. The range should not be treated as though every workload receives the same improvement or as a replacement for the named experimental conditions.

How much compilation work training requires

Figure 9 compares reinforcement learning with a supervised fully connected network using the number of compilations as the training-effort measure. The performance axis is a normalized geometric mean.

At 5,000 compilations, reinforcement learning already reaches a level only 5% below its peak and performs 1.26× better than the supervised network at that point. The supervised method reaches the corresponding level after 70,000 compilations. The authors describe this comparison as a 14× advantage in sample efficiency.

This is a stronger comparison than reporting the same number of labeled examples for both methods. Optimal supervised labels have a production cost: the candidate configurations must be compiled and evaluated. Reinforcement learning uses outcomes from its own trials without first completing that search.

Another training discussion reports useful convergence with 5,000 samples for the lowest batch-size setting and describes this as 35× fewer than exhaustive search or supervised learning would require. These statements address related but differently presented comparisons; they should not be collapsed into a single universal efficiency factor.

After training, a prediction requires a single inference step. Exhaustive search, in contrast, must evaluate alternatives again for a new case. The paper therefore distinguishes training expense from the cost of using the trained selector.

Transfer to PolyBench

PolyBench tests transfer to numerical programs dominated by loops, including matrix calculations, decomposition, and linear algebra. These workloads are particularly relevant to Polly because the paper describes Polly as optimized for this kind of computation.

The reinforcement-learning system obtains an average improvement of 3.42× over the baseline and 1.33× over Polly. It outperforms Polly on three out of the six evaluated benchmarks. Aggregate superiority therefore does not mean uniform superiority on every program.

The authors offer several explanations for cases where Polly does better. Polly can transform loops beyond selecting vectorization settings. The synthetic collection may not adequately represent the new loop structures. The compilation penalty may also discourage large settings that would otherwise be useful.

A footnote distinguishes average performance over multiple inferences from selecting the best performance. Under the latter reporting choice, the authors give an average improvement of 4.77×. That larger result describes a different selection condition and should not replace the ordinary transfer aggregate.

The paper also gives 4.35× as a potential average improvement from combining the benefits of Polly and reinforcement learning. It presents actual integration as future work. This number is therefore evidence of possible complementarity, not a measured result from a completed combined optimizer.

Transfer to MiBench

MiBench represents a different workload family. The paper describes embedded applications from areas such as networking, office tasks, and security. Loops form a smaller share of these programs than in PolyBench.

Some MiBench applications cannot be vectorized in the authors’ setup. Dependencies, control flow, or the absence of suitable loops prevent the optimization. The examples named include adpcm and dijkstra.

For the benchmarks reported in the transfer comparison, reinforcement learning exceeds both Polly and the baseline. Its average improvement over the baseline is 1.1×. Execution time is measured for complete programs, not just extracted loops.

This smaller gain is informative. An optimizer may make strong decisions where it is applicable while changing only a limited portion of total runtime. The transfer experiment therefore shows both usefulness beyond the synthetic collection and the importance of workload composition.

What the ablations show

The paper provides controlled comparisons of settings and architectural choices instead of a complete removal study of every component. These analyses help explain the behavior of the framework, but several are reported qualitatively without exact performance values.

Context helps the representation

The comparison between innermost-loop input and full loop-nest input favors the broader context. The authors explain that the larger fragment exposes access patterns, strides, and the purpose of the nested calculation.

This supports a specific representation claim: evidence outside the immediate action site can help select that action. It does not establish that more context is always better, or identify the smallest context sufficient for each loop.

The paper does not report a detailed breakdown showing which benchmark categories benefit most from the change. Its explanation is plausible and tied to program structure, but the available result does not quantify that explanation separately.

Joint prediction fits dependent settings

The authors try independent agents for VF and IF, then replace them with a joint predictor. Joint prediction works better. Their interpretation is that the settings are related and should not be optimized as independent decisions.

This is an architectural comparison with a clear practical implication. When the effect of one output depends on another, a shared decision procedure can learn combinations that separate procedures may not coordinate.

The paper does not give an exact isolated speedup for this replacement. Its evidence supports choosing the joint implementation within the framework, rather than assigning a general numerical benefit to joint prediction.

Discrete outputs work better than rounded alternatives

The action-space experiments compare direct discrete selection with continuous encodings. One continuous version uses a single output to encode the pair; another uses separate continuous outputs. The continuous values are rounded to select actual settings.

The discrete action space performs best. This suggests that the representation of the decision problem matters even when the final compiler settings come from the same finite family.

A continuous output introduces a numerical geometry that may not match how the compiler’s choices behave. The paper does not isolate that mechanism experimentally, so it remains an interpretation rather than a demonstrated cause. What the comparison establishes is the empirical preference for direct discrete choices in this setup.

Training settings affect speed and stability differently

The initial configuration uses a 64 × 64 fully connected network, a batch size of 4,000, and a learning rate of 5e-5. The authors vary settings individually and examine reward and training loss against compilation steps.

The learning rate of 5e-5 reaches the best reward fastest among the settings discussed. A rate of 5e-3 does not reach a better reward and has the highest training loss. The result argues against assuming that larger updates will produce more efficient learning.

Changing network architecture has a relatively small effect in these experiments. The authors also try shallower and deeper alternatives and describe similar outcomes. Those extra curves are not included in the figure.

Smaller batches reduce the samples needed for convergence up to a point. Below a batch size of 500, the authors observe unstable policies that do not improve on the performance achieved at that setting. Faster apparent progress and dependable final behavior are therefore different criteria.

The experiments run up to 500,000 training steps to check whether extended training yields further benefits. The policy generally converges much earlier. This provides a reason to avoid treating the full training horizon as necessary for useful results.

Simpler selectors reveal the value of the representation

Nearest-neighbor search and decision trees cannot participate in the same end-to-end training arrangement as the fully connected methods. Nevertheless, they achieve strong results when given the learned representation.

That comparison makes it harder to attribute the entire benefit to the reinforcement-learning decision mechanism alone. Part of the contribution lies in producing inputs from which several selectors can identify useful settings.

The supervised fully connected network also achieves comparable eventual performance. Reinforcement learning’s clearest advantage in that comparison concerns the amount of compilation work needed to reach strong results, instead of an assertion that supervised prediction can never match its final quality.

Transfer exposes the effect of the training objective

The compilation penalty is a practical design choice, but the PolyBench discussion reveals its possible cost. The agent can learn to avoid large factors because they risk an expensive compilation, even when a new workload might benefit from them.

This is not a clean penalty-removal ablation. It is an analysis of observed behavior on transferred workloads. The distinction matters: the paper identifies a credible limiting mechanism but does not provide a separate controlled estimate of the performance recovered by changing that penalty.

Together, these analyses show a framework whose behavior depends on representation scope, coupled outputs, action encoding, and resource policy. They do not reduce the improvement to a single component.

Limitations

Limits the authors explicitly identify

The authors acknowledge that the generated loops do not cover the full space of real programs. They connect incomplete training coverage to transfer difficulties, including unfamiliar loop bounds and structures. More examples are proposed as a route to better generalization, but the paper does not establish how much additional data would be sufficient.

Architecture dependence is another stated boundary. Different processors can favor different optimization settings and offer different action spaces. The authors propose either including architecture information in the input or training separate policies. A selector trained in the reported environment should therefore not be assumed to retain its performance on an arbitrary target.

The paper also identifies interpretability as a deployment challenge. Compiler developers may prefer decisions that are predictable, simple, and explainable. A neural representation and policy can improve measured speed without making the reason for each choice easy to inspect.

The evaluated action is local and limited. The agent selects a setting for a loop nest, while richer sequences of compiler transformations remain future work. The authors discuss extending the approach to other pragmas and to decisions at different levels of nested loops, but those possibilities are not completed experimental results.

Long compilation times create a further explicit tradeoff. The timeout makes training manageable, while the associated penalty can suppress aggressive choices. This is particularly relevant when transferring to workloads with different compilation and optimization behavior.

What the evaluation supports more narrowly

The main held-out benchmarks differ from the training examples, but both are connected to LLVM’s test ecosystem. That makes them useful for controlled evaluation while limiting how broadly their aggregate result should be interpreted. The transfer experiments add evidence from other benchmark families, yet do not amount to comprehensive coverage of application software.

The reported hardware environment is concrete. It supports comparison within that environment, instead of a claim that the same VF–IF mapping is inherently best for a source loop. Runtime is a property of the compiled program interacting with its target, not a property of source syntax alone.

Exhaustive search is also bounded. It can establish the strongest tested VF–IF pair, but it does not establish the best possible compilation strategy. Polly’s result on benchmark #10 demonstrates this directly: a transformation outside the enumerated family can beat the family’s best member.

The paper’s correctness argument rests on the compiler boundary. Inserting optimization hints leaves legality checking with LLVM. This supports the design’s constrained authority, but it is not a new formal proof of compiler correctness or a verification of arbitrary generated transformations.

A requested factor is not necessarily an enacted factor. The compiler can decline a hint when dependencies or other restrictions prevent it. As a result, the relationship among source representation, chosen action, generated code, and runtime includes compiler behavior that the agent does not directly control.

Measurement and reporting boundaries

The authors explain how they reduce timing variation in the motivating kernel and provide aggregate results for the main comparisons. However, the reported evaluations do not include confidence intervals or paired statistical tests for the headline speedups. The results demonstrate the observed outcomes without fully characterizing uncertainty around every comparison.

Average performance and best observed performance are different reporting choices. The PolyBench footnote makes that distinction explicit. A best inference can demonstrate available potential, but a deployed selector must be judged by the procedure that actually chooses its output.

Some detailed benchmark values appear only graphically. The prose supports the aggregate comparisons and particular examples discussed above, but it does not justify reconstructing exact unreported values from visual impressions of the bars.

The larger headline range in the abstract is less informative than the named benchmark results for understanding deployment. Different collections have different opportunities for vectorization, and an improvement on loop-heavy numerical code should not be transferred unchanged to a complete embedded application.

The training-efficiency comparisons are valuable because they count compilations. They nonetheless do not constitute a full accounting of every resource used by the system. Representation learning, distributed execution, measurement overhead, and deployment costs are not all summarized by the sample count alone.

Claims that remain prospective

The authors argue that reinforcement learning is well suited to larger search spaces and multiple objectives. Their runtime experiments make that proposal credible as a research direction, but do not test a broad multi-objective optimizer. Compilation time is handled primarily through a cutoff and penalty instead of a complete exploration of competing objectives.

Likewise, potential gains from combining Polly with the learned selector do not establish an integrated implementation. The methods may be complementary, but a real combination needs a defined interaction, an execution cost, and its own evaluation.

The paper sometimes describes learned code representations in very strong terms, including the preservation of information from source. The experiments establish usefulness for optimization selection, not lossless representation or complete semantic understanding. A fixed representation can work well on this task without supporting those broader conclusions.

Finally, a contextual-bandit result does not by itself solve sequential compiler optimization. When an early transformation changes what later transformations can do, the state and credit-assignment problem becomes different. The authors recognize that richer setting as a future opportunity instead of an evaluated extension.

What came after

The paper does not supply evidence about subsequent studies that adopted NeuroVectorizer, so a later citation history cannot be established here. Its own future-work discussion instead identifies several concrete continuations. These are the authors’ proposals, not results from later systems.

One continuation would replace or supplement the source representation with a polyhedral description of loops. Another would operate at the compiler’s intermediate representation, where the effects of transformations might be represented more directly. Both proposals revisit the same issue: what information should a selector observe before choosing an optimization?

A second line would combine reinforcement learning with Polly. The main experiments show that their strengths overlap only partially, and the authors suggest learning when Polly should be used. Such a system would need to evaluate the combined procedure rather than infer its performance from separate successes.

A broader extension would make sequential decisions across optimization stages or levels of a loop nest. The authors also mention tuning inlining, unrolling, and other compiler operations. That would move beyond the evaluated single-choice bandit problem toward policies whose actions reshape later opportunities.

Finally, the authors propose learning to rank candidate settings by predicted normalized runtime. That would turn the learned representation into a replacement cost estimator rather than a direct action selector. Across these directions, NeuroVectorizer’s enduring research question is precise: how can code structure and measured execution teach an optimizer to choose well without exhaustively evaluating every possibility?

Cite

Cite as Ameer Haj-Ali, Nesreen K. Ahmed, Ted Willke, Yakun Sophia Shao, Krste Asanović and Ion Gabriel Stoica. 2020. NeuroVectorizer: end-to-end vectorization with deep reinforcement learning. arXiv:1909.13639.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1145/3368826.3377928 · arXiv 1909.13639

@misc{hajali2020neurovectorizer,
  title = {{NeuroVectorizer: end-to-end vectorization with deep reinforcement learning}},
  author = {Ameer Haj-Ali, Nesreen K. Ahmed, Ted Willke, Yakun Sophia Shao, Krste Asanović and Ion Gabriel Stoica},
  year = {2020},
  doi = {10.1145/3368826.3377928},
  eprint = {1909.13639},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1145/3368826.3377928}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/ali-2020-neurovectorizer-end-end-vectorization-deep/