Elamur Research

Verified Code Transpilation with LLMs

Paper · 2024 · Sahil Bhatia, Jie Qiu, Niranjan Hasabnis et al.

Summary

An existing program may already compute the right answer, yet be written in a way that makes it hard to use a specialized compiler. A Java loop can add up selected values in a list, for instance, while a distributed computing framework expects the same calculation to be expressed as operations over a dataset. Rewriting the loop by hand creates an opportunity to change its behavior. A tool that merely produces plausible code creates the same problem at a different point. The authors develop LLMLift to automate this kind of rewrite and check that the new program has the same behavior as the original.

The method gives a code generator Python definitions of the operations available in the destination language. The generator proposes an expression made from those operations. When the source contains loops, a separate request asks for loop invariants, statements about what remains true as each loop advances. An automated theorem prover uses those statements to check whether the proposed expression and the source agree for every input covered by the formal specification. The final conversion to the destination language’s syntax happens after that check. The Python definitions allow LLMLift to work without a corpus of paired translations for each destination or additional training for that language.

The authors build compilers for four targets spanning distributed computing, switch packet processing, and tensor computation. On the Spark suite, LLMLift solves 44 of 45 benchmarks, compared with MetaLift’s 40. It matches MetaLift’s coverage on the loop-free packet-processing suite and solves all 60 benchmarks in the TACO comparison, where C2TACO solves 57. On the 23 image-processing and machine-learning kernels used to evaluate Tenspiler, both systems solve the full suite. LLMLift averages 95.89 seconds per benchmark there, compared with 115.14 seconds for Tenspiler with its search optimizations enabled. The authors report less custom search code and faster translation overall, with the size of the advantage varying across the comparisons.

The tensor experiments also show why the authors ask for the translation and its invariants separately. A single request for both yields verified translations on 20 of the 23 benchmarks. With the same stated query budget, generating the expression first and then asking for its invariants solves all 23. A proposed expression can still be malformed, compute the wrong result, or lack an invariant the prover can use. LLMLift produces a translation when the check succeeds and can exhaust its search budget without finding one.

Deep dive: Verified Code Transpilation with LLMs

LLMLift translates existing code into domain-specific operations and uses automated proofs to check that the translation preserves behavior. · about 35 minutes to read

The problem and its context

Why a correct program may still need rewriting

A domain-specific language, or DSL, gives programmers operations designed for a particular kind of work. Spark expresses computations over distributed datasets. TACO describes tensor calculations in a compact form that its compiler can use to generate optimized code. The benefit comes partly from what the programmer can leave implicit. A matrix operation can express a whole calculation that older code spells out through nested loops, assignments, and element access. When the compiler recognizes the operation, it can choose how to carry it out on the intended hardware.

Existing programs frequently express a computation at a different level. A loop reveals the order in which the author wrote down the operations. A target API may instead want a description of what happens to each element and how the results are combined. The translation has to recover that description from the loop. Even when the original code is short, getting the details right can require attention to conditions, index bounds, and intermediate values. An apparently small rewrite can change which elements contribute or where an arithmetic operation takes place.

The paper uses transpilation for translating a program from one language to another. It calls the move from relatively low-level, general-purpose code to a higher-level DSL lifting. A lift into Spark or a tensor language makes an existing calculation available to a compiler designed for that domain. The hope is that the target system can take advantage of the higher-level form. The immediate task for a lifting tool is to find that form while preserving the calculation.

The paper treats the source program as a specification. If the source returns a certain value for a particular input, the target must return the same value for that input. This gives the translator a concrete obligation even when the source comes with little documentation. It also sets the boundary of the task. A rewrite checked against the original implements the original behavior, including a surprising choice that the original made deliberately or by mistake. The author’s unstated intention provides no additional condition for the prover to check.

How earlier lifting systems found a translation

The paper describes rule-based translators that match shapes in source programs and replace them with target constructs. A rule can work well when a recognizable form has a known replacement. Writing the collection of rules is the hard part. Source code can express the same computation in different ways, and a rule writer has to anticipate which forms should count as instances of the same operation. Connecting low-level source patterns to a particular target interface also ties the rule set to that source and target.

Verified lifting shifts part of this work into program synthesis, the search for a program that meets a specification. A developer describes the space of candidate target expressions. The synthesizer searches that space, and a formal verifier checks the proposed result against the source. The paper places prior compilers for SQL, Spark, Halide, and TACO in this tradition. They show that a translation can be generated and checked automatically once the search and verification machinery are in place.

A grammar is one way to describe the candidate space. It can allow expressions that start with input variables and build larger terms by applying target operations. Syntax-guided synthesis combines such a syntactic restriction with a semantic requirement. The syntax specifies what a solution may look like. The semantic requirement specifies what it must compute. A candidate can meet either condition by itself. For lifting, success requires both.

A grammar can admit enough expressions to make search expensive. An enumerative synthesizer may try small expressions before considering larger ones. The number of ways to combine operations and arguments grows as the expressions become more elaborate. Deductive and constraint-based techniques offer other ways to guide search. Earlier tools also use domain-specific heuristics designed to make plausible candidates easier to reach. The paper identifies the design and implementation of those heuristics as a substantial part of building a lifting compiler.

Neural guidance offers another way to steer synthesis. The authors discuss earlier work in which a neural system learns to accelerate the search. In the approach they describe, doing so requires paired source and target examples suitable for training. A new DSL can make such a collection difficult to assemble. The cost of adapting symbolic search lies in the search description and heuristics. The cost of adapting a learned search can lie in collecting representative translations. Both matter when the aim is to support another target API.

Why generation and verification belong together

The authors situate LLMLift alongside earlier work on general-purpose program translation, code generation, and formal verification. They describe Unsupervised Translation of Programming Languages as translating among C++, Java, and Python. LLMLift tackles a different kind of translation, where the target can require operations specialized for an application domain and the compiler must check equivalence to the source. The authors also cite work using language generation to propose program invariants and other ingredients for proofs. Their compiler brings candidate programs and the annotations needed to check them into the same workflow.

The paper illustrates the difficulty of asking for the final syntax directly. It gives GPT-3.5 a C++ function and asks for TACO code. The answer calls functions outside TACO’s API and fails to provide the expected tensor expression. The example exposes a failure that can arise before reasoning about correctness. A generator can infer enough about the domain to produce convincing-looking names and still fail to express the calculation in the actual target language. An expression built from real operations would have to clear a further hurdle by computing what the source computes.

The authors use a familiar programming language to describe what the target operations mean. This lets the generator read the permitted API as executable-looking definitions and reason about how those definitions combine. Verification then judges the proposed combination. The search mechanism can change without changing the meaning of a successful equivalence check. That division of labor comes from classical verified lifting. LLMLift changes how candidates and proof annotations reach the checker.

The method, step by step

Describe the destination in terms of its operations

The compiler developer starts with the operations that make sense for a destination. For Spark, the paper illustrates the idea with map and reduce. A mapping operation applies a function to the elements of a dataset and collects the results. A reduction combines the elements using a supplied operation, such as addition. Python definitions give these operations a meaning that can be used to reason about values. The mapping definition describes what comes out of a map while leaving the mechanics of distributed execution to Spark.

These definitions form an intermediate representation, or IR. A program expressed in this representation makes choices about which target operations to use and how to connect them. It can leave details such as the target API’s call syntax until later. The authors call the expression that represents the source computation a program summary, abbreviated PS. Here, a summary is a program in its own right. Its meaning is determined by the supplied operator definitions, and it must account for the value returned by the source.

Python serves as the notation for the definitions and for the proposed expressions. The authors choose it because of its compact syntax, broad use, and substantial presence in code training data. They ask for expressions in a restricted part of the language. That restriction matters because the expression must be understood by the parser and translated into the verifier’s language. A general Python program could bring in arbitrary loops or operations that the downstream tools have no rule for handling.

Writing a Python definition and writing a rewrite rule serve different purposes. The definition says what a DSL operation does. A rule for the final backend says how to express a call to that operation in the destination. The paper’s approach depends on these descriptions corresponding to each other. For a new target, the compiler developer must still provide the permitted operations and their meaning, along with the rules used to translate the accepted expression. The proposed saving is in the work of designing a search that knows how to put those operations together.

How LLMLift produces a verified translation

The steps in order.

How LLMLift produces a verified translationStep 1: Define target operations in Python1. Define target operations in PythonStep 2: Propose an expression for the source computation2. Propose an expression for the source computationStep 3: Reject candidates outside the permitted syntax3. Reject candidates outside the permitted syntaxStep 4: Propose invariants for source loops when needed4. Propose invariants for source loops when neededStep 5: Translate the proof obligations for the verifier5. Translate the proof obligations for the verifierStep 6: Check equivalence to the source6. Check equivalence to the sourceStep 7: Render the verified expression in target syntax7. Render the verified expression in target syntax

Propose a target expression

The prompt for the program summary presents a task in natural language, the permitted operations as Python definitions, and the source code to translate. The instruction asks for a rewrite built from the definitions. The source supplies the specification directly. An author need not first turn it into a collection of example input-output pairs or express its desired behavior in a specialized verification language before making the request.

This part of the system uses a zero-shot prompt. In the paper’s setup, zero-shot means the prompt includes the task and definitions but contains no worked translation for the generator to imitate. Operator definitions still give substantial information. They explain the effect of each call and constrain which vocabulary an answer can use. The task is to read the source, recognize the computation it carries out, and express that computation with the vocabulary already supplied.

The Java example shows what such recognition involves. The source walks a list of integers, adding an element to an accumulator if it is less than 100. In the proposed expression, a mapping operation keeps each qualifying integer and substitutes 0 for the others. A reduction then sums the mapped values. An element that fails the condition makes no contribution to the sum. Accordingly, the body of the source loop can be captured by a per-element rule, and the loop’s accumulating behavior can be captured by a reduction.

The expression uses a conditional inside the mapping operation. That keeps the test associated with the element being processed. The reduction needs only the addition rule. The program summary thus expresses a relationship that a direct syntax conversion would have to discover anyway. The source contains a loop, a condition, and an update. The expression contains a map and a reduction that together describe the same calculation. Recognizing which constructs can be grouped this way is the job delegated to generation.

The parser checks the answer before the verification stage. It can reject a call to an operation that the prompt did not authorize or a construct outside the supported representation. The check serves a practical purpose even when an answer is valid Python. Its role is to establish that the compiler has a defined way to interpret and lower the expression. Once a candidate passes, its syntax permits a semantic check. The verifier still has to determine what the expression computes and whether that computation agrees with the source.

State the equivalence obligation

The paper first presents the broad search goal as finding a target program that agrees with the source across the allowed input states. In Unicode notation, that objective is:

∃ T ∈ Tₗₐₙ𝓰 : ∀ σ, S(σ) = T(σ)

The symbol ∃ means that a suitable program exists. T denotes the candidate target program, ∈ means membership, and Tₗₐₙ𝓰 denotes the target program language. The colon introduces the condition that the chosen program must satisfy. ∀ means “for every,” and σ is an input state. S is the source program. Applying each program to the state gives S(σ) and T(σ), and the equality sign compares those results.

A useful target expression has to belong to the target language as well as compute the right result. In the Java example, another sequential implementation of the same loop could return identical values yet be unsuitable for the compiler. The lifting task asks for an expression in the vocabulary of the intended destination. The existential part of the formula captures the search for one such program. The universal part makes the proposed program answerable to the source over the input domain.

The authors formalize their setting with source and target programs treated as side-effect-free functions of their inputs. They write the specification as a predicate and give its meaning through equality of returned values:

(∀ σ, ϕ(σ, T, S)) = (∀ σ, S(σ) = T(σ))

Here ϕ is the specification predicate. Its arguments name the state σ, the candidate T, and the source S. The quantifier ∀ ranges over input states on each side. The outer = identifies the condition on the left with the condition on the right. The inner = is equality of program results. Parentheses around each quantified clause make clear that the left side says the specification holds for all states, and the right side says what it means for that to happen.

This formulation tells the reader what the proof concerns. A source can build up its return value through local assignments while the target computes that value through a single expression. The verifier has to account for those local updates on the way to the result. The returned value is the comparison the formal specification calls for. Runtime, allocation choices, and the order in which a distributed backend schedules work are different properties.

The search has a specification, a space of admissible programs, and a procedure for finding candidates. The paper calls the procedure A. In symbolic lifting, it might enumerate expressions, derive them deductively, or solve constraints that determine them. LLMLift uses prompts and repeated proposals to carry out this part of the process. The candidate language and the obligation to show equivalence still constrain what counts as a solution.

Supply a relationship that holds inside each loop

The program summary describes a whole calculation. A source loop exposes intermediate states that a verifier must reason about to connect the start of the calculation to its result. A loop invariant is a statement that holds when the loop starts and is preserved by the loop body whenever another iteration takes place. A useful invariant also gives enough information at loop exit to prove the desired property. A statement can be true throughout a loop and still be too weak for the final argument.

In the list example, an index bound supplies part of the required information. It tells the verifier that the loop index refers to a valid position in the traversal, including the point at which the entire list has been processed. The central claim relates the accumulator to that index. After processing a prefix of the list, the accumulator should equal the same map-and-reduce calculation applied to that prefix. The relationship explains what the partial result means at each step.

At the start, no elements have been processed. The invariant must match the starting accumulator under the representation’s definitions. During an iteration, the source either adds the current element or leaves the accumulator as it is. The corresponding map operation contributes either that element or 0. Extending the prefix and updating its sum therefore fits the relationship stated by the invariant. On exit, the prefix covers the input, so the invariant relates the final accumulator to the full program summary.

The paper describes a template for this kind of statement:

Inv ≜ f(i) ∧ e(Tₗₐₙ𝓰)

Inv is the invariant, and ≜ introduces its definition. The function-like notation f(i) denotes a condition over the loop indices, represented by i. The connective ∧ requires both parts to hold. The term e(Tₗₐₙ𝓰) denotes a condition constructed using operations from the target language Tₗₐₙ𝓰. In the list example it relates an intermediate source variable, the accumulator, to a target expression evaluated on part of the input.

The bound in that example is written as:

0 ≤ i ≤ len(data)

0 is the initial index bound, i is the loop index, and ≤ means “less than or equal to.” The call len(data) gives the length of the input list, named data. The chained comparison places the index between the beginning of the traversal and the position marking its completion. The upper bound can include the length because the invariant also describes the state in which there is no next element to read.

A proof usually needs to connect several questions about these statements. Does the source initialization establish the invariant? Can an iteration beginning in a state that satisfies it leave a state that violates it? When the loop condition says to stop, does the invariant establish the relationship required by the proposed summary? Giving the prover an invariant turns a question about arbitrarily many iterations into obligations about these relationships. The generator supplies the statement. The verifier determines whether it can support the argument.

Generate the annotations for the actual candidate

LLMLift asks for invariants after a program summary has passed the initial syntax check. The request includes the source and adds an assertion relating its return value to that particular proposed summary. This matters if the generator can express the same computation in several ways. An invariant that characterizes a partial result with one set of operations may be easier to use when the final expression uses the same operations and intermediate relationships.

The invariant prompt uses one-shot learning. It includes a worked example so that the generator sees what a loop annotation looks like in this setting. The example uses element-wise matrix subtraction, where matching positions in the input matrices determine the entries in the output. It illustrates how separate invariants can express progress through loops operating at different levels of a matrix calculation.

The prompt imposes restrictions on the form of the answer. It asks for a separate invariant for each loop and for a Boolean expression that uses the allowed definitions. Conditions are inlined, and the annotation uses a single return statement and no loop of its own. The intended representation lets the parser turn the result into a formula. Giving the annotation ordinary conditional logic and the permitted operators makes its structure more predictable than allowing arbitrary code that computes a Boolean value.

In the source example, the return-value assertion supplies a destination for the proof. At the end, the source accumulator must agree with the reduction over the full mapped list. The generator can work from that destination to propose what the accumulator should mean partway through. The prompt needs to convey both facts. An invariant is about an intermediate state of the source, and the particular target summary describes the result that the verifier will ultimately compare with the source.

The approach uses prompt context, without DSL-specific fine-tuning. The matrix example in the invariant prompt demonstrates the form of a useful answer. It serves a different function from a parallel corpus of translated programs used to learn a new target language. The representation of the permitted DSL operators changes with the target. The general prompt structure gives those definitions the same role across the domains evaluated in the paper.

Search for a program and annotations that can be checked together

The paper combines the program and annotation searches in a more detailed statement of verified lifting:

∃ PS ∈ G, ∃ Inv ∈ Gᵢ, ∀ σ, ϕ(σ, PS, Inv, S)

PS is the candidate program summary. G describes the permitted space of summaries, usually with a context-free grammar. Inv denotes the loop invariants, and Gᵢ is the space of permitted invariants. ∃ asks for a choice from each space, with membership indicated by ∈. ∀ σ says the condition must hold for every input state σ. The predicate ϕ expresses the specification for the source S when checked using the summary and accompanying invariants. The commas separate the quantifiers and the condition they govern.

A context-free grammar describes which expression structures can be built by combining smaller ones. The underlying idea is recursive. Input variables can appear as terms, and allowed operations can take terms as arguments to form larger expressions. In classical synthesis the grammar can guide the order and form of search directly. In LLMLift the supplied definitions and instructions guide proposal, while the parser turns some of the same restrictions into enforceable checks. A natural-language request alone gives no guarantee that the candidate will use the allowed expression forms.

The paper’s pseudocode describes a bounded loop over proposed summaries. It keeps track of summaries already processed. For each new summary that parses, the search asks for candidate invariants and avoids repeated checks of an invariant for that summary. Parseable combinations go to the verifier. Success ends the search and supplies the summary that will be rendered in the destination syntax.

If the available invariant attempts fail, the algorithm records the summary as unsuccessful and moves on. Later requests include previously unsuccessful summaries with a request for something different. This is an economical search decision. Repeating an earlier expression could consume another round of attempts without adding anything new. At the same time, failure of the attempts leaves open the possibility that the summary was correct and needed a different proof annotation. The algorithm can run out of attempts and return no translation.

Loop-free source functions provide a simpler case. Since there is no intermediate state across loop iterations to characterize with an invariant, the verifier can check the proposed summary without the separate annotation round. The packet-processing evaluation exercises that case. It still needs syntax checks and a semantic comparison, so it isolates a setting in which the generator’s job is to propose the right target expression alone.

Check the candidate and emit the destination code

The compiler translates the accepted forms of the Python summary and annotations into expressions the verification system can handle. The background names cvc5 and Z3 as theorem provers used for verified lifting. The paper discusses SMT-LIB as a standard representation for satisfiability modulo theories, or SMT. An SMT check can reason about formulas that combine logical conditions with operations such as arithmetic. LLMLift uses translation rules to reach the verification notation. Asking directly for this notation would give the generator a language the authors say is less well represented in its training data.

The verifier uses the encoded source, the program summary, and any required invariants to check equivalence. An annotation has to meet the demands of the proof. A program summary has to agree with the source under the specification. An expression can look convincing and satisfy all the parser’s rules while still failing that check. The successful proof, rather than the confidence or style of the proposed answer, is what permits compilation to continue.

The final rewrite has a smaller job than source-to-source lifting. In the Java example, the verified expression already identifies a mapping operation, its per-element function, a reduction, and the addition used to combine values. Rendering that expression in Spark form arranges the calls in the target API’s syntax. The compiler has already settled which computation to express. The rendering rules map that settled expression to the destination language without having to infer it again from Java control flow.

The method therefore includes two translations after generation, each with its own purpose. One prepares formulas for checking. The other produces executable target code from an expression whose meaning has been checked. Input to the first includes the proof annotations. Input to the second is the summary itself. The invariants help justify why the low-level source computes the result, so the destination expression does not need to carry those invariants as runtime operations.

Experiments and results

What the evaluation measures

The experiments compare verified lifting compilers on the source programs they are asked to translate. The common outcome is a solved benchmark. In a setting with loops, solving includes producing a usable target expression and sufficient annotations to establish equivalence. In the loop-free setting, verification can proceed without loop annotations. This definition matters for reading the paper’s accuracy figures. They measure successful translation and checking across programs in a benchmark suite, rather than the fraction of test inputs on which a particular unverified guess returned the expected answer.

The authors use GPT-4 through an API for candidate generation and set its temperature to 0.7 across the experiments. Temperature is a setting that affects variation in generated answers. The study gives a budget of 50 queries for program summaries and 10 queries for each summary’s invariants. The same zero-shot structure for summaries and the same one-shot structure for annotations are used across the domains. The domain-specific operator definitions determine what kinds of output each instance can use.

The authors make the evaluation benchmarks available. For the main comparisons, the paper uses programs associated with the symbolic systems against which LLMLift is evaluated. This permits a comparison on the same tasks, including tasks each prior compiler was designed to address. A later synthetic experiment changes the construction of the tasks to explore a particular difficulty for C2TACO. The paper reports solved cases, time to obtain a solution, and the scale of some of the search code or prompt material needed for the implementations.

A translation time includes the work needed to produce a verified solution in the compiler evaluation. It is different from the execution time of the emitted program. The end result may give Spark, a switch, or a tensor compiler access to specialized operations. The reported times address how quickly the lifting system arrives at that result. The baseline comparisons also involve different time limits or search budgets, so the time and coverage figures are easiest to interpret within each domain.

From Java loops to Spark

The distributed computing experiment translates sequential Java to the Apache Spark API. Spark is useful here because operations on datasets express opportunities for data parallelism. The translation has to recover those operations from code that may traverse and update values sequentially. The earlier list example illustrates how a sequential accumulation can become a map followed by a reduction, though the evaluation covers a broader benchmark suite.

The baseline is MetaLift, which uses Rosette for symbolic search. The authors use the same 45 benchmarks as MetaLift. All contain loops, so a translation in this experiment needs loop invariants as well as a program summary. This is important to the comparison. A system that recovered a plausible Spark expression for a difficult benchmark but supplied no proof material would still have work left to do.

MetaLift solves 40 of the 45 benchmarks with a timeout of 1 hour. LLMLift solves 44. According to the authors, there are four additional benchmarks that LLMLift handles but MetaLift fails to finish within the time limit. That result captures a difference in what the systems reach under their respective search constraints. It also shows that the generator can find annotations good enough to establish the targeted equivalence on cases where the symbolic search fails to finish.

Verified translations on the Spark benchmark suite

LLMLift verifies more translations than MetaLift on the Java-to-Spark tasks.

Verified translations on the Spark benchmark suiteMetaLift: 40MetaLift40LLMLift (this paper): 44LLMLift (this paper)44
The numbers
System or settingbenchmarks solved
MetaLift40
LLMLift (this paper)44

The authors report that LLMLift solves a Spark benchmark in less than 1 minute on average, while MetaLift averages 3 minutes. They also describe MetaLift’s search-space descriptions for summaries and invariants as amounting to approximately 1000 lines of code. LLMLift’s implementation still has to describe the operators. The comparison concerns the additional specification of where and how a symbolic synthesizer should look for expressions and proof annotations.

The Spark evaluation illustrates the cost of solving the two problems together. A candidate summary must fit the source computation. The verification also needs a useful account of loop progress in terms of that summary. A lifting system can spend its search effort on either part, and the solved count reflects success at both. The paper does not report separate mean times for finding the program summary and establishing the proof in this domain.

From packet transactions to switch operations

The packet-processing experiment uses Domino benchmarks written in a subset of C. The earlier Domino compiler turns an algorithm expressed as a packet transaction into operations supported by a programmable switch. The paper calls those operations atoms. An atom represents work the hardware can carry out as a unit, and a sequence of such operations determines how the switch is configured for the transaction.

To build the LLMLift version, the authors supply the meanings of the atoms in the prompt. The baseline is MetaLift’s Domino implementation. The source programs here contain no loops. The evaluation therefore tests whether the system can recover an equivalent program expressed in the switch’s operations and establish its correctness without asking for loop invariants.

Both systems solve all 10 Domino benchmarks. MetaLift averages 6 seconds per benchmark, and LLMLift averages 2 seconds. The authors describe MetaLift’s search-space description for the program summaries as roughly 1100 lines of code. LLMLift gets the permitted vocabulary from the definitions of the atoms. The measured difference is in search time and the reported difference in implementation concerns the custom search description. Coverage is already complete for the symbolic baseline.

The absence of loops makes this evaluation distinct from the Spark case. Each success can be attributed to finding an appropriate expression and checking it, without the additional question of whether the generator could formulate a suitable invariant. The result shows that the main generation-and-checking path also applies in a setting that does not require the paper’s full two-phase procedure.

From C++ to TACO tensor expressions

TACO accepts tensor calculations expressed in a compact notation resembling Einstein summation, where shared indices can express how tensor entries contribute to a result. A C++ implementation may instead express the calculation through the values assigned at individual indices. Lifting to TACO requires recovering an expression compatible with the target vocabulary. The symbolic C2TACO tool tackles this by searching among expressions composed of tensor operations and index variables.

The authors compare both systems on 60 benchmarks and use the original C2TACO evaluation’s 90 mins timeout for each benchmark. C2TACO solves 57, while LLMLift solves all 60. The 3 cases C2TACO misses require expressions of depth greater than 4, according to the main experiment discussion. Extending the timeout for those cases to 1 day still yields no C2TACO solution. This is evidence about the expressions the search reached in those runs.

An average solve takes 41 seconds for C2TACO and 2 seconds for LLMLift. The paper gives a sense of the adaptation work behind the two implementations. C2TACO uses over 1000 lines of code for its search heuristics. LLMLift’s task instructions and operator meanings are contained in a prompt of 100 lines. The reported counts refer to different parts of the two systems. They indicate how the authors supplied domain information to the search in this comparison.

The suite-level result contains both ties and improvements. BLAS, DSP, DSPStone, and makespeare each have 100% accuracy for both tools. Both also reach 100% on UTDSP. The remaining suites expose the difference in coverage. On mathfu, LLMLift reaches 100% and C2TACO reaches 91.6%. On simpl_array, the corresponding accuracies are 100% and 90%. On darknet, they are 100% and 92.8%. Each figure refers to the share of programs solved in that named suite.

The chart uses the average solve time across the TACO evaluation. The per-suite coverage figures answer a separate question. A search may handle a collection of routine expressions quickly while still struggling to reach a few larger expressions. Coverage and time together capture both parts of the comparison.

Average solve time on the TACO benchmark suite

LLMLift takes less time on average to produce a verified TACO translation.

Average solve time on the TACO benchmark suiteC2TACO: 41C2TACO41LLMLift (this paper): 2LLMLift (this paper)2
The numbers
System or settingseconds
C2TACO41
LLMLift (this paper)2

From sequential code to a common tensor representation

The other tensor experiment uses the intermediate representation introduced by Tenspiler. This target includes operations such as element-wise arithmetic, reductions, and transposition. A common representation allows a source computation to be lifted once and expressed for supported backends through further compilation. The paper describes the representation as serving 6 hardware and software backends. The comparison measures lifting into the representation on a suite from image processing and machine-learning kernels.

Tenspiler and LLMLift both solve all 23 benchmarks in that suite. LLMLift supplies the annotations needed for verification as part of those results. For the full suite, the authors report a mean solve time of 95.89 seconds per benchmark for LLMLift and 115.14 seconds for Tenspiler. The Tenspiler measurement uses its optimizations enabled. Those optimizations are part of the system as designed, and the full system is the appropriate baseline for the direct time and coverage comparison.

The paper also reports approximately 1200 lines of code for Tenspiler’s three domain-specific search optimizations. The LLMLift instantiation does without manually supplied search heuristics of that kind. The target is nonetheless described through its operations, and the verifier still needs a supported representation in which to check the results. This comparison illustrates what the prompt-based search replaces in the compiler development process.

The image and kernel tasks have longer reported solve times than some other domains in the paper. The paper does not assign the difference to a particular verification or generation cost. The experiment establishes the mean time and coverage for the two systems on this suite. It also provides a demanding setting in which the authors can vary the prompt procedure and ask how often they still obtain successful proofs.

Reading the paper’s cross-domain claims

Across the symbolic comparisons, the authors report 7 additional solved benchmarks for LLMLift and an average speed advantage of 6×. The Spark and TACO suites account for the increases in coverage. The packet-processing and Tenspiler comparisons show matched coverage. This spread matters. In one case the traditional tool had already solved the whole suite, while in another the baseline’s search missed expressions that the new system found.

The paper also gives a headline figure of 1000× for the reduction in implementation effort measured in lines of code. The domain accounts identify the work being replaced more concretely. MetaLift is described in terms of search-space descriptions, C2TACO in terms of heuristic code, and Tenspiler in terms of implemented optimizations. The TACO comparison explicitly counts lines of prompt material on the LLMLift side. These quantities document the reduction in handwritten search machinery more directly than they measure total compiler size or developer time.

The practical claim supported across the cases is that a common generation procedure can use different descriptions of target operations and still produce candidates that pass formal verification. The coverage results show where that worked. The solve times show how quickly the compilers established it for the tested tasks. Transpilation provides a way to access target-specific execution facilities, but evaluating those facilities would require measuring the translated programs themselves.

What the ablations show

Generate the program before its invariants

The main LLMLift ablation changes when the program expression and the invariants are proposed. In the standard procedure, a zero-shot request produces the summary. A later one-shot request includes that summary and asks for the proof annotations. For the alternative, the authors merge the requests into a single prompt with a worked example of producing both together. This evaluates a joint proposal of the expression and proof material against the procedure that fixes the expression before asking for the proof material.

The authors run the comparison on the tensor-processing DSL, which has 37 operators and is described as their most complex target. Budget constraints limit the test to that domain. The alternative is given the same stated query budget as the standard approach. Joint generation solves 20 of the 23 benchmarks. Generating the program summary first and then the invariants solves all 23.

Verified translations by prompt procedure on the tensor-processing suite

Generating the program summary before its invariants yields more verified translations.

Verified translations by prompt procedure on the tensor-processing suiteJoint summary and invariant generation: 20Joint summary and invariant generation20Separate summary and invariant generation (this paper): 23Separate summary and invariantgeneration (this paper)23
The numbers
System or settingbenchmarks solved
Joint summary and invariant generation20
Separate summary and invariant generation (this paper)23

The authors suggest that requesting both at once increases the difficulty of the generation task. A suitable expression has to be found while also constructing annotations that connect the expression to the internal states of the source. With the staged procedure, a later prompt can refer to the exact operations and arrangement in the chosen expression. The generator can focus on asking what partial value would develop into that result.

The comparison also changes how the worked example and the candidate-specific assertion are presented. The merged prompt teaches the joint format, while the staged procedure makes the particular translation available as a fixed input to the annotation request. The result therefore supports the staged procedure as implemented. It does not identify how much of the improvement comes from narrower tasks, the explicit assertion, the example format, or the opportunity to reuse a program summary across different annotation attempts.

The outcome is measured in completed verifications. A joint attempt can fail because the expression is wrong, because the invariant is wrong or too weak, or because one of the outputs cannot be parsed. The reported solved counts establish that these difficulties blocked more benchmarks under the joint procedure. The study does not give a breakdown of which difficulty accounted for each of the joint procedure’s missed cases.

Remove Tenspiler’s domain-specific optimizations

The Tenspiler comparison includes a separate intervention on the baseline. The authors disable all three search optimizations and allow a timeout of 1 hour. With the optimizations removed, Tenspiler solves 5 of the 23 benchmarks. Its full configuration solves all 23. This result tests the contribution of the optimizations as a group to symbolic search on the same image-processing and machine-learning kernel tasks.

With its optimizations, Tenspiler reaches solutions throughout the suite. Removing them makes far fewer of those solutions accessible within the allowed time. The result connects the paper’s implementation-cost argument to an observable effect. The search code contributed to the baseline’s ability to cover the suite. The direct performance comparison uses that complete baseline, while the removal test shows what the custom search machinery contributes.

The experiment gives no individual effect for each optimization. Their combined effect can include interactions, such as one optimization leaving a smaller search space for another to handle. The result measures the consequences of disabling the group. LLMLift reaches the full suite through a different proposal mechanism, so it demonstrates that the tested tasks can be solved without reproducing those optimizations in its own search.

Increase expression size for C2TACO

The synthetic C2TACO experiment probes what happens when a benchmark demands a longer expression than many of the original cases. The paper uses an example in which the source raises every element of an array to the power of 4. C2TACO searches in increasing order of expression length using its tensor operations and index variables. The authors report that it enumerates approximately 30k candidates in the example. This illustrates how many candidates can precede a suitable expression even when the underlying operation is easy to state in words.

The authors randomly generate 10 additional benchmarks with expression lengths from 5 to 10 and a variety of arithmetic operations. C2TACO solves none within the 90 minutes used for the experiment. LLMLift solves all 10 correctly in less than 2 seconds, as reported by the authors. They also try a variant that raises array elements to the power of 20 and report that LLMLift generates a correct solution efficiently. They give no specific solve time for that variant.

This comparison changes the benchmark distribution to probe the enumerator. It complements the main suite, where the authors identify the missed expressions by depth. The synthetic suite is described in terms of expression length. Those measures can both indicate more involved expressions, and the paper gives no general conversion between them. What the synthetic result shows directly is that the chosen longer expressions defeated C2TACO within its time limit while remaining accessible to the generator and verifier.

A proposal mechanism can recognize a pattern from the source and jump directly to a likely composition. An enumerator that progresses by length can spend time examining many shorter expressions first. That distinction explains why this test is informative about the particular search strategies. It says less about other ways of enumerating tensor expressions or about larger programs whose difficulty comes from control flow or proof obligations instead of expression length.

Inspect the errors caught along the way

The qualitative analysis looks at individual attempts for a screen-blending kernel. The source combines the base and active pixel values, then subtracts a correction derived from their product and a fixed divisor of 255. The computation is performed across matrix positions. A plausible translation should therefore express the element-wise operations and preserve the arithmetic that determines the correction.

Some proposals use Python loops or list comprehensions. These can read like reasonable implementations of the computation, yet fall outside the form supported by the compiler’s path into the verifier. In this case, the parser stops them. The example clarifies why using Python as the intermediate notation still requires an explicit boundary around what can be generated and translated. The subset the compiler supports determines when a Python expression can participate in the proof.

Other proposals use acceptable operator calls and still change the calculation. The paper shows expressions that construct a different correction term using matrix operations and the constant 32. A reader can recognize the broad shape of screen blending in these answers, with products, divisions, and sums involving the inputs. That resemblance is insufficient to establish equivalence when the operation determining the correction has changed. These candidates reach semantic checking and are rejected there.

The examples illustrate why both checks have independent work to do. Syntax checking identifies expressions the compiler cannot interpret through its supported rules. Semantic checking evaluates expressions that have a defined interpretation and may still produce the wrong result. The paper reports examples of each failure, which explain how errors arise and where the system handles them. It does not estimate how frequently each kind of error occurs across the full evaluation.

Limitations

Limits identified by the authors

The formal problem is stated for source and target programs treated as side-effect-free functions of their inputs. The guarantee concerns equality of returned values under that formulation. An extension to programs whose observable behavior includes external state changes would need a specification and verification encoding that describe those changes. The study neither defines nor evaluates a general equivalence procedure for such behavior.

The authors also identify a representational constraint. Asking for a specialized DSL or verification notation directly can lead to nonexistent constructs and other generation failures. Python makes the operator descriptions easier to work with, but candidate output can still exceed the supported subset. Such output is rejected. The choice of a familiar notation helps at the point of proposal, while the availability of lowering rules still determines which expressions can be checked.

The authors make the search bounded. Its failure result means that the run ended without a verified candidate. That outcome can follow from a shortage of suitable summaries, insufficient invariants for a good summary, or candidates that the parser cannot translate. The algorithm may even treat a potentially useful summary as unsuccessful once it has tried the available invariants for it. Verification makes an accepted candidate meaningful without making candidate generation complete.

The authors explicitly limit their comparison of joint and separate prompting to the tensor-processing target because of budget constraints. That is where they show the improvement in solve count. The loop-free Domino tasks require no invariant request, and the other loop-containing suites do not receive the same controlled comparison. The observed advantage is evidence for the procedure on the target where it was tested.

Limits of what the setup demonstrates

The correctness claim has a boundary at the formal encoding. The verifier reasons over the encoded source and the defined meanings of the operators in the intermediate representation. For the executable target program to inherit that result, the source encoding must capture the intended source behavior, the supplied definitions must capture the relevant target operation behavior, and the final rewrites must preserve the verified expression’s meaning. These are requirements of the method. The evaluation is an assessment of the compilers built around those representations instead of an independent proof of every represented backend.

This distinction matters when a computation depends on details that can vary between representations, such as arithmetic conventions or the allowed inputs to a reduction. An equivalence proof applies to the semantics represented in its obligations. Generalizing it to different arithmetic or edge-case behavior would require encoding that behavior and establishing the relevant obligations again. The paper’s examples and formal statement give the reader the intended comparison of returned values, without characterizing every possible source or target language feature.

The evaluation also ties the observed success to GPT-4 and to the stated sampling settings and budgets. The same prompt structure appears across multiple targets, which shows some reuse. The paper does not report repeated-run distributions that would tell a reader how variable the solved counts and timings are across runs. It gives no basis for estimating the probability that a particular benchmark will be solved with fewer queries, a different generator, or another formulation of the same definitions.

The benchmark suites offer useful comparisons with existing tools because those tools have been run on the same tasks. They represent particular domains and program forms. The synthetic TACO cases add evidence specifically about arithmetic-expression size. Together they leave open how this search behaves on long functions, functions with complicated interactions among loops, or targets whose permitted operators and proof obligations require substantially different representations. A new DSL also calls for accurate definitions and rewrite rules, even if the search procedure can be reused.

Timeouts and query budgets support a comparison under the conditions of the experiment. They do not settle whether an unsuccessful system can ever find a solution. This is especially relevant in the TACO cases. The original timeout, the additional day-long runs, and the synthetic experiment show persistent difficulties for the tested enumerative strategy. They cannot establish the performance of an altered search ordering, a revised grammar, or a different symbolic synthesizer on those inputs.

The reported engineering effort has a similarly specific scope. Lines of code give a countable view of symbolic heuristics, search descriptions, and optimizations. Prompt length gives a view of how much task-specific material was written for one generation setup. Neither supplies a direct measure of the time needed to design and validate operator definitions, implement source support, or maintain backend mappings. The comparisons support the paper’s argument about reducing custom search work, while the overall effort for an unfamiliar destination remains an open measurement.

Finally, the paper is about obtaining a verified translation. The execution speed of the resulting target program, the efficiency of its generated hardware code, and the quality of any optimization choices would require their own comparisons. A summary can compute the appropriate result without being the fastest way to express it in the DSL. The method’s successful termination rule is based on equivalence. The evaluated outcome is reaching that rule with a suitable program and proof.

What came after

Formal Mathematical Reasoning: A New Frontier in AI cites LLMLift. The citation connects code transpilation to the broader subject of formal reasoning. In LLMLift, the generated objects are a candidate program and statements about its source loops. The reasoning system checks those objects against a defined obligation. This gives a concrete example of how a generated proposal can participate in a formal argument whose validity is determined separately.

The citing work’s specific use of LLMLift is undocumented here. The citation establishes a connection between the works, with no reported extension, replication, or new application of the transpilation procedure that can be attributed to it.

Cite

Cite as Sahil Bhatia, Jie Qiu, Niranjan Hasabnis, Sanjit A. Seshia and Alvin Cheung. 2024. Verified Code Transpilation with LLMs. arXiv:2406.03003.

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

@misc{bhatia2024verified,
  title = {{Verified Code Transpilation with LLMs}},
  author = {Sahil Bhatia, Jie Qiu, Niranjan Hasabnis, Sanjit A. Seshia and Alvin Cheung},
  year = {2024},
  doi = {10.48550/arxiv.2406.03003},
  eprint = {2406.03003},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2406.03003}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bhatia-2024-verified-code-transpilation-llms/