Title: CLN2INV: LEARNING LOOP INVARIANTS WITH CONTINUOUS LOGIC NETWORKS

Abstract: Program verification offers a framework for ensuring program correctness and therefore systematically eliminating different classes of bugs. Inferring loop invariants is one of the main challenges behind automated verification of real-world programs, which often contain many loops. In this paper, we present the Continuous Logic Network (CLN), a novel neural architecture for automatically learning loop invariants directly from program execution traces. Unlike existing neural networks, CLNs can learn precise and explicit representations of formulas in Satisfiability Modulo Theories (SMT) for loop invariants from program execution traces. We develop a new sound and complete semantic mapping for assigning SMT formulas to continuous truth values that allows CLNs to be trained efficiently. We use CLNs to implement a new inference system for loop invariants, CLN2INV, that significantly outperforms existing approaches on the popular Code2Inv dataset. CLN2INV is the first tool to solve all 124 theoretically solvable problems in the Code2Inv dataset. Moreover, CLN2INV takes only 1.1 second on average for each problem, which is 40× faster than existing approaches. We further demonstrate that CLN2INV can even learn 12 significantly more complex loop invariants than the ones required for the Code2Inv dataset. * Co-student leads listed in alphabetical order; each contributed equally.

1. INTRODUCTION:

Program verification offers a principled approach for systematically eliminating different classes of bugs and proving the correctness of programs. However, as programs have become increasingly complex, real-world program verification often requires prohibitively expensive manual effort (Wilcox et al., 2015; Gu et al., 2016; Chajed et al., 2019) . Recent efforts have focused on automating the program verification process, but automated verification of general programs with unbounded loops remains an open problem (Nelson et al., 2017; 2019) .

Verifying programs with loops requires determining loop invariants, which captures the effect of the loop on the program state irrespective of the actual number of loop iterations. Automatically inferring correct loop invariants is a challenging problem that is undecidable in general and difficult to solve in practice (Blass & Gurevich, 2001; Furia et al., 2014) . Existing approaches use stochastic search (Sharma & Aiken, 2016) , heurstics-based search (Galeotti et al., 2015) , PAC learning based on counterexamples (Padhi & Millstein, 2017) , or reinforcement learning (Si et al., 2018) . However, these approaches often struggle to learn complex, real-world loop invariants.

In this paper, we introduce a novel approach to learning loop invariants by modeling the loop behavior from program execution traces with a new type of neural architecture. We note that inferring loop invariants can be posed as learning formulas in Satisfiability Modulo Theories (SMT) (Biere et al., 2009) over program variables collected from program execution traces (Nguyen et al., 2017) . In principle, neural networks are well suited to this task because they can act as universal function approximators and have been successfully applied in various domains that require modeling of arbitrary functions (Hornik et al., 1989; Goodfellow et al., 2016) . However, loop invariants must be represented as explicit SMT formulas to be usable for program verification. Unfortunately, existing methods for extracting logical rules from general neural architectures lack sufficient precision (Augasta & Kathirvalavakumar, 2012) , while inductive logic learning lacks sufficient expressiveness for use in verification (Evans & Grefenstette, 2018) .

We address this issue by developing a novel neural architecture, Continuous Logic Network (CLN), which is able to efficiently learn explicit and precise representations of SMT formulas by using continuous truth values. Unlike existing neural architectures, CLNs can represent a learned SMT formula explicitly in its structure and thus allow us to precisely extract the exact formula from a trained model.

In order to train CLNs, we introduce a new semantic mapping for SMT formulas to continuous truth values. Our semantic mapping builds on BL, or basic fuzzy logic (Hájek, 2013) , to support general SMT formulas in a continuous logic setting. We further prove that our semantic model is sound (i.e., truth assignments for the formulas are consistent with their discrete counterparts) and complete (i.e., all formulas can be represented) with regard to the discrete SMT formula space. These properties allow CLNs to represent any quantifier-free SMT formula operating on mixed integer-real arithmetic as an end-to-end differentiable series of operations.

We use CLNs to implement a new inference system for loop invariants, CLN2INV, that significantly outperforms state-of-the-art tools on the Code2Inv dataset by solving all 124 theoretically solvable problems in the dataset. This is 20 problems more than LoopInvGen, the winner of the SyGus 2018 competition loop invariant track (Padhi & Millstein, 2017) . Moreover, CLN2INV finds invariants for each program in 1.1 second on average, more than 40 times faster than LoopInvGen. We also demonstrate that CLN2INV is able to learn complex, real-world loop invariants with combinations of conjunctions and disjunctions of multivariable constraints. Our source code and benchmarks are publicly available on Github1 .

Our main contributions are:

• We introduce a new semantic mapping for assigning continuous truth values to SMT formulas that is theoretically grounded and enables learning formulas through backpropagation. We further prove that our semantic model is sound and complete.

• We develop a novel neural architecture, Continuous Logic Networks (CLNs), that to the best of our knowledge is the first to efficiently learn precise and explicit SMT formulas by construction.

• We use CLNs to implement a new loop invariant inference system, CLN2INV, that is the first to solve all 124 theoretically solvable problems in the Code2Inv dataset, 20 more than the existing methods. CLN2INV is able to find invariants for each problem in 1.1 second on average, 40× faster than existing systems.

• We further show that CLN2INV is able to learn 12 more complex loop invariants than the ones present in the Code2Inv dataset with combinations of multivariable constraints.

Related Work. Traditionally, loop invariant learning relies on stochastic or heuristics-guided search (Sharma & Aiken, 2016; Galeotti et al., 2015) . Other approaches like NumInv analyze traces and discover conjunctions of equalities by solving a system of linear equations (Sharma et al., 2013; Nguyen et al., 2017) . LoopInvGen uses PAC learning of CNF using counterexamples (Padhi et al., 2016; Padhi & Millstein, 2017) . By contrast, Code2Inv learns to guess loop invariants using reinforcement learning with recurrent and graph neural networks (Si et al., 2018) . However, these approaches struggle to learn complex invariants. Unlike these works, CLN2INV efficiently learns complex invariants directly from execution traces.

There is extensive work on PAC learning of boolean formulas, but learning precise formulas requires a prohibitively large number of samples (Kearns et al., 1994) . Several recent works use differentiable logic to learn boolean logic formulas from noisy data (Kimmig et al., 2012; Evans & Grefenstette, 2018; Payani & Fekri, 2019) or improving adversarial robustness by applying logical rules to training (Fischer et al., 2019) . By contrast, our work learns precise SMT formulas directly by construction, allowing us to learn richer predicates with compact representation in a noiseless setting.

A variety of numerical relaxations have been applied to SAT and SMT solving. Application-specific approximations using methods such as interval overapproximation and slack variables have been developed for different classes of SMT (Eggers et al., 2008; Nuzzo et al., 2010) . More recent work has applied recurrent and graph neural networks to Circuit SAT problems and unsat core detection (Amizadeh et al., 2019; Selsam et al., 2019; Selsam & Bjørner, 2019) . FastSMT uses embeddings from natural language processing like skip-gram and bag-of-words to represent formulas for search strategy optimization (Balunovic et al., 2018) . Unlike these approaches, we relax the SMT semantics directly to generate a differentiable representation of SMT.

2. BACKGROUND:

In this section, we introduce the problem of inferring loop invariants and provide a brief overview of Satisfiability Modulo Theories (SMT), which are used to represent loop invariants. We provide background into fuzzy logic, which we extend with our new continuous semantic mapping for SMT.

2.1. LOOP INVARIANTS:

Loop invariants capture loop behavior irrespective of number of iterations, which is crucial for verifying programs with loops. Given a loop, while(LC){C}, a precondition P , and a postcondition Q, the verification task involves finding a loop invariant I that can be concluded from the precondition and implies the post-condition (Hoare, 1969) . Formally, it must satisfy the following three conditions, in which the second is a Hoare triple describing the loop:

P =⇒ I {I ∧ LC} C {I} ¬LC ∧ I =⇒ Q

Example of Loop Invariant. Consider the example loop in Fig. 1 . For a loop invariant to be usable, it must be valid for the precondition (t = 10 ∧ u = 0), the inductive step when t = 0, and the post-condition (u = 20) when the loop condition is no longer satisfied, i.e., t = 0. The correct and precise invariant I for the program is (2t + u = 20).

//pre: t=10 /\ u=0 while (t != 0){ t = t -1; u = u + 2; } //post: u=20

(a) Example loop

The desired loop invariant I for the left program is a boolean function over program variables t, u such that:

∀t u, t = 10 ∧ u = 0 =⇒ I(t, u) (pre) I(t, u) ∧ (t = 0) =⇒ I(t -1, u + 2) (inv) I(t, u) ∧ (t = 0) =⇒ u = 20 (post) (b)

The desired and precise loop invariant I is (2t + u = 20). 

2.2. SATISFIABILITY MODULO THEORIES:

Satisfiability Modulo Theories (SMT) are an extension of Boolean Satisfiability that allow solvers to reason about complex problems efficiently. Loop invariants and other formulas in program verification are usually encoded with quantifier-free SMT. A formula F in quantifier-free SMT can be inductively defined as below:

F := E 1 E 2 | ¬F | F 1 ∧ F 2 | F 1 ∨ F 2 ∈ {=, =, <, >, ≤, ≥}

where E 1 and E 2 are expressions of terms. The loop invariant (2t + u = 20) in Fig. 1 is an SMT formula. Nonlinear arithmetic theories admit higher-order terms such as t 2 and t * u, allowing them to express more complex constraints. For example, (¬(2 ≥ t 2 )) is an SMT formula that is true when the value of the high-order term t 2 is larger than 2.

2.3. BASIC FUZZY LOGIC (BL):

Basic fuzzy logic (BL) is a class of logic that uses continuous truth values in the range [0, 1] and is differentiable almost everywhere2 (Hájek, 2013) . BL defines logical conjunction with functions called t-norms, which must satisfy specific conditions to ensure that the behavior of the logic is consistent with boolean First Order Logic. Formally, a t-norm (denoted ⊗) in BL is a binary operator over truth values in the interval [0, 1] satisfying the following conditions:

1. associativity and commutativity: the order in which a set of t-norms on continuous truth values are evaluated should not change the result: x⊗(y⊗z) = (x⊗y)⊗z and x⊗y = y⊗x. 2. monotonicity: increasing any input value to a t-norm operation should not cause the result to decrease: x 1 ≤ x 2 =⇒ x 1 ⊗ y ≤ x 2 ⊗ y 3. consistency: the result of any t-norm applied to a truth value and 1 should be 1, and the result of any truth value and 0 should be 0: 1 ⊗ x = x and 0 ⊗ x = 0

Besides these conditions, BL also requires that t-norms be continuous. Given a t-norm ⊗, its associated t-conorm (denoted ⊕) is defined with DeMorgan's law: t ⊕ u ¬(¬t ⊗ ¬u), which can be considered as logical disjunction. A common t-norm is the product t-norm x ⊗ y = x • y with its associated t-conorm x ⊕ y = x + y -x • y.

3. CONTINUOUS SATISFIABILITY MODULO THEORIES:

We introduce a continuous semantic mapping, S, for SMT on BL that is end-to-end differentiable.

The mapping S associates SMT formulas with continuous truth values while preserving each formula's semantics. In this paper, we only consider quantifier-free formulas. This process is analogous to constructing t-norms for BL, where a t-norm operates on continuous logical inputs.

We define three desirable properties for continuous semantic mapping S that will preserve formula semantics while facilitating parameter training with gradient descent:

1. S(F ) should be consistent with BL. For any two formulas F and F , where F (x) is satisfied and F (x) is unsatisfied with an assignment x of formula terms, we should have S(F )(x) < S(F )(x). This will ensure the semantics of SMT formulas are preserved. 2. S(F ) should be differentiable almost everywhere. This will facilitate training with gradient descent through backpropogation. 3. S(F ) should be increasing everywhere as the terms in the formula approach constraint satisfaction, and decreasing everywhere as the terms in the formula approach constraint violation. This ensures there is always a nonzero gradient for training.

Continuous semantic mapping. We first define the mapping for ">" (greater-than) and "≥" (greater-than-or-equal-to) as well as adopting definitions for "¬", "∧", and "∨" from BL. All other operators can be derived from these. For example, "≤" (less-than-or-equal-to) is derived using "≥" and "¬", while "=" (equality) is then defined as the conjunction of formulas using "≤" and "≥." Given constants B > 0 and > 0, we first define the the mapping S on ">" and "≥" using shifted and scaled sigmoid functions:

S(t > u) 1 1 + e -B(t-u-) S(t ≥ u) 1 1 + e -B(t-u+ )

We illustrate these functions in Figure 2 . The validity of our semantic mapping lie in the following facts, which can be proven with basic algebra. When goes to zero and B * goes to infinity, our continuous mapping of ">" and "≥" will preserve their original semantics. Under these conditions, our mapping satisfies all three desirable properties. In practice, for small and large B, the properties are also satisfied if |t -u| > .

lim →0 + B• →+∞ 1 1 + e -B(t-u-) = 1 t > u 0 t ≤ u lim →0 + B• →+∞ 1 1 + e -B(t-u+ ) = 1 t ≥ u 0 t < u

Next we define the mapping S for boolean operators "∧", "∨" and "¬" using BL. Given a specific t-norm ⊗ and its corresponding t-conorm ⊕, it is straightforward to define mappings of "∧", "∨" and "¬":

S(F 1 ∧ F 2 ) S(F 1 ) ⊗ S(F 2 ) S(F 1 ∨ F 2 ) S(F 1 ) ⊕ S(F 2 ) S(¬F ) 1 -S(F )

Based on the above definitions, the mapping for other operators can be derived as follows:

S(t < u) = S(¬(t ≥ u)) = 1 1 + e B(t-u+ ) S(t ≤ u) = S(¬(t > u)) = 1 1 + e B(t-u-) S(t = u) = S((t ≥ u) ∧ (t ≤ u)) = 1 1 + e -B(t-u+ ) ⊗ 1 1 + e B(t-u-)

Figure 2The mapping S on "=" is valid since the following limit holds (see Appendix A for the proof).

lim →0 + B• →+∞ S(t = u) = lim →0 + B• →+∞ 1 1 + e -B(t-u+ ) ⊗ 1 1 + e B(t-u-) = 1 t = u 0 t = u

The mapping for other operators shares similar behavior in the limit, and also fulfill our desired properties under the same conditions.

Using our semantic mapping S, most of the standard operations of integer and real arithmetic, including addition, subtraction, multiplication, division, and exponentiation, can be used normally and mapped to continuous truth values while keeping the entire formula differentiable. Moreover, any expression in SMT that has an integer or real-valued result can be mapped to continuous logical values via these formulas, although end-to-end differentiability may not be maintained in cases where specific operations are nondifferentiable.

4. CONTINUOUS LOGIC NETWORKS:

In this section, we describe the construction of Continuous Logic Networks (CLNs) based on our continuous semantic mapping for SMT on BL.

CLN Construction. CLNs use our semantic mapping to provide a general neural architecture for learning SMT formulas. In a CLN, the learnable coefficients and smoothing parameters correspond to the learnable parameters in a standard feedforward network, and the continuous predicates, tnorms, and t-conorms operate as activation functions like ReLUs in a standard network. In this paper, we focus on shallow networks to address the loop invariant inference problem, but we envision deeper general purpose CLNs that can learn arbitrary SMT formulas. When constructing a CLN, we work from an SMT Formula Template, in which every value is marked as either an input term, a constant, or a learnable parameter. Given an SMT Formula Template, we dynamically construct a CLN as a computational graph. Figure 3 shows a simple formula template and the constructed CLN. We denote the CLN model constructed from the formula template S(F ) as M F .

CLN Training. Once the CLN has been constructed based on a formula template, it is trained with the following optimization. Given a CLN model M constructed from an SMT template with learnable parameters W, and a set X of valid assignments for the terms in the SMT template, the expected value of the CLN is maximized by minimizing a loss function L that penalizes model outputs that are less than one. A minimum scaling factor β is selected, and a hinge loss is applied to the scaling factors (B) to force the differentiable predicates to approach sharp cutoffs. The offset is also regularized to ensure precision. The overall optimization is formulated as:

max {W,B, } E[M (X; W, B, )] = min {W,B, } x∈X L(M (x; W, B, )) + λ B∈B L hinge (β, B) + γ|| || 2

where λ and γ are hyperparameters respectively governing the weight assigned to the scaling factor and offset regularization. L hinge (β, B) is defined as max(0, β -B), and L is any loss function strictly decreasing in domain [0, 1].

Given a CLN that has been trained to a loss approaching 0 on a given set of valid assignments, we show that the resulting continuous SMT formula learned by the CLN is consistent with an equivalent discrete SMT formula. In particular, we prove that such a formula is sound, (i.e., a CLN will learn a correct SMT formula with respect to the training data), and that our continuous mapping is complete, (i.e., CLNs can represent any SMT formula that can be represented in discrete logic), where these properties are defined for CLNs as follows:

Soundness. Given the SMT formula F , the CLN model M F constructed from S(F ) always preserves the truth value of F . It indicates that given a valid assignment to the terms x in F ,

F (x) = T rue ⇐⇒ M F (x) = 1 and F (x) = F alse ⇐⇒ M F (x) = 0.

Completeness. For any SMT formula F , a CLN model M can be constructed representing that formula. In other words, CLNs can express all SMT formulas on integers and reals.

We further prove that CLNs are guaranteed to converge to a globally optimal solution for formulas, which can be expressed as the conjunction of linear equalities. We provide formal definitions and proofs for soundness and completeness in Appendix B and optimality in Appendix C.

5. LOOP INVARIANT LEARNING:

We use CLNs to implement a new inference system for loop invariants, CLN2INV, which learns invariants directly from execution traces. CLN2INV follows the same overall process as other loop invariant inference systems such as LoopInvGen and Code2Inv -it iterates through likely candidate invariants and checks its validity with an SMT solver. The key difference between our method and other systems is that it learns a loop invariant formula directly from trace data. Figure 3 provides an overview of the architecture.

Preprocessing. We first perform static analysis and instrument the program to prepare for training data generation. In addition to collecting the given precondition and post-condition, the static analysis extracts all constants in the program, along with the loop termination condition. We then instrument the program to record all program variables before each loop execution and after the loop termination. We also restrict the loop to terminate after a set number of iterations to prevent loops running indefinitely (for experiments in this paper, we set the max loop iterations to 50). We also strengthen the precondition to ensure loop execution (see Appendix D).

Training Data Generation. We generate training data by running the program repeatedly on a set of randomly initialized inputs that satisfy the preconditions. Unconstrained variables are initialized from a uniform distribution centered on 0 with width r, where r is a hyperparameter of the sampling process. Variables with either upper or lower bound precondition constraints are initialized from a uniform distribution adjacent to their constraints with width r, while variables with both upper and lower bounds in the precondition are sampled uniformly within their bounds. For all of our experiments in this paper, we set r to 10. When the number of uninitialized variables is small (i.e., less than 3), we perform this sampling exhaustively. An example of training data generation is provided in Appendix E.

Template Generation. We generate templates in three stages with increasing expressiveness:

1. We first generate templates directly from the pre-condition and post-condition.

2. We next extract the individual clauses from the pre-and post-condition as well as the loop condition, and generate templates from conjunctions and disjunctions of each possible pair of clauses.

3. We finally generate more generic templates of increasing complexity with a combination of one or more equality constraints on all variables combined with conjunctions of inequality constraints, which are based on the loop condition and individual variables.

We describe the template generation in detail in Appendix E. To detect when higher order terms may be present in the invariant, we perform a log-log linear regression on each variable relative to the loop iteration, similarly to Sharma et al. (2013) . If the loop contains one or more variables that grow superlinearly relative to the loop iteration, we add higher order polynomial terms to the equality constraints in the template, up to the highest degree detected among the loop variables.

CLN Construction and Training. Once a template formula has been generated, a CLN is constructed from the template using the formulation in §4. As an optimization, we represent equality constraints as Gaussian-like functions that retain a global maximum when the constraint is satisfied as discussed in Appendix F. We then train the model using the collected execution traces.

Invariant Checking. Invariant checking is performed using SMT solvers such as Z3 (De Moura & Bjørner, 2008) . After the CLN for a formula template has been trained, the SMT formula for the loop invariant is recovered by normalizing the learned parameters. The invariant is checked against the pre, post, and inductive conditions as described in §2.1. If the correct invariant is not found, we return to the template generation phase to continue the search with a more expressive template.

6. EXPERIMENTS:

We compare the performance of CLN2INV with two existing methods and demonstrate the efficacy of the method on several more difficult problems. Finally, we conduct two ablation studies to justify our design choices.

Test Environment. All experiments are performed on an Ubuntu 18.04 server with an Intel Xeon E5-2623 v4 2.60GHz CPU, 256Gb of memory, and an Nvidia GTX 1080Ti GPU.

System Configuration. We implement CLNs in PyTorch and use the Adam optimizer for training with learning rate 0.01 (Paszke et al., 2017; Kingma & Ba, 2014) . Because the performance of CLN is dependent on weight initialization, the CLN training randomly restart if the model does not reach termination within 2, 000 epochs. Learnable parameters are initialized from a uniform distribution in the range [-1, 1], which we found works well in practice.

Test Dataset. We use the same benchmark used in the evaluation of Code2Inv. We have removed nine invalid programs from Code2Inv's benchmark and test on the remaining 124. The removed programs are invalid because there are inputs which satisfy the precondition but result in a violation of the post-condition. See Appendix G for details on the removed problems. The benchmark consists of loops expressed as C code and corresponding SMT files. Each loop can have nested if-then-else blocks (without nested loops). Programs in the benchmark may also have uninterpreted functions with boolean return values (emulating external function calls) in branches or loop termination conditions. Performance Comparison. We compare CLN2INV to two state-of-the-art methods: Code2Inv (based on neural code representation and reinforcement learning) and LoopInvGen (PAC learning over synthesized CNF formulas) (Si et al., 2018; Padhi & Millstein, 2017) . We limit each method to one hour per problem in the same format as the SyGuS Competition (Alur et al., 2019) . CLN2INV is able to solve all 124 problems in the benchmark. LoopInvGen solves 104 problems while Code2inv solves 90.3 

6.1. COMPARISON TO EXISTING SOLVERS:

Figure 4a shows the measured runtime on each evaluated system. CLN2INV solves problems in 1.1 second on average, which is over 40× faster than LoopInvGen, the second fastest system in the evaluation. It spends the most time on solver calls (0.6s avg.) and CLN training (0.5s avg.), with negligible time spent on preprocessing, data generation, and template generation on each problem ( less than 20ms ea.) 4 .

In Table 1 we provide a more detailed analysis of how much time is spent on each stage of the invariant inference pipeline in CLN2INV. Measurements are averaged over 5 runs. The system spends most time on solver calls (0.6s avg.) and CLN training (0.5s on avg.) with negligible time spent on preprocessing, sampling, and template generation. For most problems in the Code2Inv benchmark, CLN2INV completes CLN training quickly (less than 0.2s) and spends most of its time performing solver checks, but it requires more epochs to train on some complex problems with many variables. In general, CLN2INV has similar performance to LoopInvGen on simple problems but is able to scale efficiently to complex problems. Figure 4b shows the number of Z3 calls made by each method. For almost all problems, CLN2INV requires fewer Z3 calls than the other systems, although for some difficult problems it uses more Z3 calls than Code2Inv.

Table 2 summarizes results of the performance evaluation. Code2Inv require much more time on average per problem, but minimizes the number of calls made to an SMT solver. In contrast, Loop-InvGen is efficient at generating a large volume of guessed candidate invariants, but is much less accurate for each individual invariant. CLN2INV can be seen as balance between the two approaches: it searches over candidate invariants more quickly than Code2Inv, but generates more accurate invariants than LoopInvGen, resulting in lower overall runtime.

6.2. MORE DIFFICULT LOOP INVARIANTS:

We consider two classes of more difficult loop invariant inference problems that are not present in the Code2Inv dataset. The first require conjunctions and disjunctions of multivariable constraints, and the second require polynomials with many higher order terms. Both of these classes of problems are significantly more challenging because they are more complex and cause the space of possible invariants to grow much more quickly.

To evaluate on problems that require invariants with conjunctions and disjunctions of multivariable constraints, we construct 12 additional problems. We specifically design these problems to contain loops with invariants that cannot be easily inferred with pre-and post-condition based heuristics. In this section Figure 5 , we show one of these problems. By plotting the trace as shown in Figure 5b , it is easy to see that the points lie on one of the two lines expressible as linear equality constraints.

The correct loop invariant for the program is Another problem with multivariable conjunction is shown in Figure 6 . In this program, we use unknown to denote an external function call that returns either true or false. As we cannot assume much about the function, we model the function call as sampling from a Bernoulli distribution with success probability 0.5. Although the branching behavior is may not be deterministic, we know

((t + u = 0) ∨ (t -u = 0)) ∧ (u ≤ 0).

(t + u = 0) ∧ (v + w = 0) ∧ (u + w ≥ 0

) is a correct invariant, as it holds regardless of which branch is taken. Our CLN2INV can learn this invariant within 20 seconds, while both Code2inv and LoopInvGen time out after one hour without finding a solution.

To evaluate on problems with higher order polynomial invariants, we test CLN2INV on the power summation problems in the form u = k t=0 t d for a given degree d, which have been used in evaluation for polyonomial loop invariant inference (Sharma et al., 2013; Nguyen et al., 2017) . We discuss these problems in more detail in Appendix H. CLN2INV can correctly learn the invariant for 1st and 2nd order power summations, but cannot learn correct invariants for 3rd, 4th or 5th order //pre: t=-10 /\ u=10 /\ v=-10 /\ w=10 while (u + w > 0) { if (unknown()) { t++; u--; } else { v++; w--; } } //post: t=w /\ u=v Figure 6 : Pseudocode for Problem 2, which involves a conjunction of equalities summations, which have many more higher order terms. We do not evaluate the other methods on these problems because they are not configured for nonlinear arithmetic by default.

6.3. ABLATION STUDIES:

Effect of CLN Training on Performance. CLN2INV relies on a combination of heuristics using static analysis and learning formulas from execution traces to correctly infer loop invariants. In this ablation we disable model training and limit CLN2INV to static models with no learnable parameters. Static CLN2INV solves 91 problems in the dataset. Figure 7 shows a comparison of full CLN2INV with one limited to static models. CLN2INV's performance with training disabled shows that a large number of problems in the dataset are relatively simple and can be inferred from basic heuristics. However, for more difficult problems, CLN learning is key to inferring correct invariants. 

7. CONCLUSION:

We develop a novel neural architecture that explicitly and precisely learns SMT formulas by construction. We achieve this by introducing a new sound and complete semantic mapping for SMT that enables learning formulas through backpropagation. We use CLNs to implement a loop invariant inference system, CLN2INV, that is the first to solve all theoretically solvable problems in the Code2Inv benchmark and takes only 1.1 second on average. We believe that the CLN architecture will also be beneficial for other domains that require learning SMT formulas.

PROOF OF LIMIT OF S(t = u)

lim →0 + B• →+∞ S(t = u) = lim →0 + B• →+∞ 1 1 + e -B(t-u+ ) ⊗ 1 1 + e B(t-u-) = 1 t = u 0 t = u Proof. Let f (t, u; B, ) = 1 1+e -B(t-u+ ) and g(t, u; B, ) = 1 1+e B(t-u-)

. Then what we want to prove becomes lim

→0 + B• →+∞ (f (t, u; B, ) ⊗ g(t, u; B, )) = 1 t = u 0 t = u

Because all f, g, ⊗ are continuous in their domain, we have lim

→0 + B• →+∞ (f (t, u; B, ) ⊗ g(t, u; B, )) =   lim →0 + B• →+∞ f (t, u; B, )   ⊗   lim →0 + B• →+∞ g(t, u; B, )   Using basic algebra, we get lim →0 + B• →+∞ f (t, u; B, ) = 1 t ≥ u 0 t < u lim →0 + B• →+∞ g(t, u; B, ) = 1 t ≤ u 0 t > u

Combing these results, we have   lim

→0 + B• →+∞ f (t, u; B, )   ⊗   lim →0 + B• →+∞ g(t, u; B, )   = 0 ⊗ 1 t < u 1 ⊗ 1 t = u 1 ⊗ 0 t > u

For any t-norm, we have 0 ⊗ 1 = 0, 1 ⊗ 1 = 1, and 1 ⊗ 0 = 0. Put it altogether, we have lim

→0 + B• →+∞ (f (t, u; B, ) ⊗ g(t, u; B, )) = 1 t = u 0 t = u

which concludes the proof.

B SOUNDNESS AND COMPLETENESS OF CLNS:

In this section we provide formal descriptions and proofs of CLN soundness and completeness when trained to 0 loss. These properties are defined for CLNs as follows:

Soundness. Given the SMT formula F , the CLN model M F constructed from S(F ) always preserves the truth value of F . It indicates that given a valid assignment to the terms x in F ,

F (x) = T rue ⇐⇒ M F (x) = 1 and F (x) = F alse ⇐⇒ M F (x) = 0.

Completeness. For any SMT formula F , a CLN model M can be constructed representing that formula. In other words, CLNs can express all SMT formulas on integers and reals.

We formally state these properties in Theorem 1. Before that we need to define a property for t-norms.

Property 1. ∀t u, (t > 0) and (u > 0) implies (t ⊗ u > 0).

The product t-norm and Godel t-norm have this property, while the Lukasiewicz t-norm does not. Theorem 1. For any quantifier-free linear SMT formula F , there exists CLN model M , such that

∀x B , 0 ≤ M (x; B, ) ≤ 1 (1) ∀x, F (x) = T rue ⇐⇒ lim →0 + B• →∞ M (x; B, ) = 1 (2) ∀x, F (x) = F alse ⇐⇒ lim →0 + B• →∞ M (x; B, ) = 0 (3)

as long as the t-norm used in building M satisfies Property 1.

Proof. For convenience of the proof, first remove all <, ≤, = and = in F , by transforming t < u into ¬(t ≥ u), t ≤ u into ¬(t > u), t = u into (t ≥ u) ∧ ¬(t > u), and t = u into (t > u) ∨ ¬(t ≥ u). Now the only operators that F may contain are >, ≥, ∧, ∨, ¬. We prove Theorem 1 by induction on the constructor of formula F . In the following proof, we construct model M given F and show that it satisfied Eq.(1)(2). We leave the proof for why M also satisfied Eq.(3) to readers.

Atomic Case. When F is an atomic clause, then F will be in the form of x * W + b > 0 or x * W + b ≥ 0. For the first case, we construct a linear layer with weight W and bias b followed by a sigmoid function scaled with factor B and right-shifted with distance . For the second case, we construct the same linear layer followed by a sigmoid function scaled with factor B and left-shifted with distance . Simply evaluating the limits for each we arrive at ∀x, F (x) = T rue ⇐⇒ lim

→0 + B• →∞ M (x; B, ) = 1

And from the definition of sigmoid function we know 0 ≤ M (x; B, ) ≤ 1.

Negation Case. If F = ¬F , from the induction hypothesis, F can be represented by models M satisfying Eq.(1)(2)(3). Let p output node of M . We add a final output node p = 1 -p . So M (x; B, ) = 1 -M (x; B, ). Using the induction hypothesis 0 ≤ M (x; B, ) ≤ 1, we conclude Eq.( 1) 0 ≤ M (x; B, ) ≤ 1. Now we prove the " =⇒ " side of Eq.( 2). If F (x) = T rue, then F (x) = F alse. From the induction hypothesis, we know lim

→0 + B• →∞ M (x; B, ) = 0. So lim →0 + B• →∞ M (x; B, ) = lim →0 + B• →∞ 1 -M (x; B, ) = 1 -0 = 1 Next we prove the " ⇐= " side. If lim →0 + B• →∞ M (x; B, ) = 1, we have lim →0 + B• →∞ M (x; B, ) = lim →0 + B• →∞ 1 -M (x; B, ) = 1 -1 = 0

From the induction hypothesis we know that F (x) = F alse. So F (x) = ¬F (x) = T rue.

Conjunction Case. If F = F 1 ∧ F 2 , from the induction hypothesis, F 1 and F 2 can be represented by models M 1 and M 2 , such that both (F 1 , M 1 ) and (F 2 , M 2 ) satisfy Eq.(1)(2)(3). Let p 1 and p 2 be the output nodes of M 1 and M 2 . We add a final output node p = p 1 ⊗ p 2 . So M (x; B, ) = M 1 (x; B, ) ⊗ M 2 (x; B, ). Since (⊗) is continuous and so are M 1 (x; B, ) and M 2 (x; B, ), we know their composition M (x; B, ) is also continuous. (Readers may wonder why M 1(x; B, ) is continuous. Actually the continuity of M (x; B, ) should be proved inductively like this proof itself, and we omit it for brevity.) From the definition of (⊗), we have Eq.( 1) 0 ≤ M (x; B, ) ≤ 1. Now we prove the =⇒ side of Eq.(2). For any x, if F (x) = T rue which means both F 1 (x) = T rue and F 2 (x) = T rue, from the induction hypothesis we know that lim

→0 + B• →∞ M 1 (x; B, ) = 1 and lim →0 + B• →∞ M 2 (x; B, ) = 1. Then lim →0 + B• →∞ M (x; B, ) = lim →0 + B• →∞ M 1 (x; B, ) ⊗ M 2 (x; B, ) = 1 ⊗ 1 = 1

Then we prove the ⇐= side. From the induction hypothesis we know that M 1 (x; B, ) ≤ 1 and M 2 (x; B, ) ≤ 1. From the non-decreasing property of t-norms (see §2.3), we have

M 1 (x; B, ) ⊗ M 2 (x; B, ) ≤ M 1 (x; B, ) ⊗ 1

Then from the consistency property and the commutative property, we have

M 1 (x; B, ) ⊗ 1 = M 1 (x; B, )

Put them altogether we get

M (x; B, ) ≤ M 1 (x; B, ) ≤ 1 Corollary 1. For any quantifier-free linear formula F , ∀x B , 0 ≤ S(F ; B, )(x) ≤ 1 ∀x, F (x) = T rue ⇐⇒ lim →0 + B• →∞ S(F ; B, )(x) = 1 ∀x, F (x) = F alse ⇐⇒ lim →0 + B• →∞ S(F ; B, )(x) = 0

Corollary 1 indicates the soundness of S. The second part is that we construct a CLN model given S(F ). In other words, we translate S(F ) into vertices in a computational graph composed of differentiable operations on continuous truth values.

C OPTIMALITY OF CLNS:

Optimality. For a subset of SMT formulas (conjunctions of multiple linear equalities), CLNs are guaranteed to converge at the global minimum. We formally state this in Theorem 2. We first define another property similar to strict monotonicity.

Property 2. ∀t 1 t 2 t 3 , (t 1 < t 2 ) and (t 3 > 0) implies (t 1 ⊗ t 3 < t 2 ⊗ t 3 ).

Theorem 2. For any CLN model M F constructed from a formula, F , by the procedure shown in the proof of Theorem 1, if F is the conjunction of multiple linear equalities then any local minimum of M F is the global minimum, as long as the t-norm used in building M F satisfies Property 2.

Proof. Since F is the conjunction of linear equalities, it has the form

F = n i=1 ( li j=1 w ij t ij = 0)

Here W = {w ij } are the learnable weights, and {t ij } are terms (variables). We omit the bias b i in the linear equalities, as the bias can always be transformed into a weight by adding a constant of 1 as a term. For convenience, we define f

(x) = S(x = 0) = 1 1+e -B(x+ ) ⊗ 1 1+e B(x-) .

Given an assignment x of the terms {t ij }, if we construct our CLN model M F following the procedure shown in the proof of Theorem 1, the output of the model will be

M (x; W, B, ) = n i=1 f ( li j=1 w ij t ij )

When we train our CLN model, we have a collection of m data points {t ij1 }, {t ij2 }, ..., {t ijm }, which satisfy formula F . If B and are fixed (unlearnable), then the loss function will be

EQUATION

Suppose W * = {w * ij } is a local minima of L(W). We need to prove W * is also the global minima. To prove this, we use the definition of a local minima. That is,

EQUATION

For convenience, we denote u ik = li j=1 w ij t ijk . Then we rewrite Eq.(4) as

L(W) = m k=1 L( n i=1 f (u ik )) If we can prove at W * , ∀ 1 ≤ i ≤ n, 1 ≤ k ≤ m, u ik = 0.

Then because (i) f reaches its global maximum at 0, (ii) the t-norm (⊗) is monotonically increasing, (iii) L is monotonically decreasing, we can conclude that W * is the global minima.

we prove ∀ 1 ≤ i ≤ n, 1 ≤ k ≤ m, u ik = 0. Here we just show the case i = 1. The proof for i > 1 can be directly derived using the associativity of (⊗).

Let α k = n i=2 f (u ik ). Since f (x) > 0 for all x ∈ R, using Property 2 of our t-norm (⊗), we know that α k > 0. Now the loss function becomes

L(W) = m k=1 L(f (u 1k ) ⊗ α k )

From Eq.( 5), we have

EQUATION

Because (i) f (x) is an even function decreasing on x > 0 (which can be easily proved), (ii) (⊗) is monotonically increasing, (iii) L is monotonically decreasing, for -δ < γ < 0, we have

EQUATION

Combing Eq.( 6) and Eq.( 7), we have

m k=1 L(f (u ik (1 + γ)) ⊗ α k ) = m k=1 L(f (u ik ) ⊗ α k )

Now we look back on Eq.( 7). Since (i) L is strictly decreasing, (ii) the t-norm we used here has Property 2 (see §4 for definition), (iii) α k > 0, the only case when (=) holds is that for all 1 ≤ k ≤ m, we have f

(|u ik (1 + γ)|) = f (|u ik |). Since f (x) is strictly decreasing for x ≥ 0, we have |u ik (1 + γ)| = |u ik |.

Finally because -1 < -δ < γ < 0, we have u ik = 0.

template::

Construct a template given an smt formula. extract clauses:

Extract individual clauses from smt formulas. estimate degrees:

Performs log-log linear regression to estimate degree of each variable. polynomial kernel:

Executes polynomial kernel on variables and data for a given degree. is single constraint:

Checks if condition is a single inequality constraint. extract loop constraint: Converts the loop condition to learnable smt template.

Note that templates are generated on demand, so each template is used to infer a possible invariant before the next is generated. for eq clause in eq clauses do template len ← template len + 1 31: end while

F PROPERTIES OF GAUSSIAN FUNCTION:

We use a Gaussian-like function u) = exp(-(t-u) 2 2σ2 ) to represent equalities in our experiments. It has the following two properties. First, it preserves the original semantic of = when σ → 0, similar to the mapping S(t = u) = Executing the program with these inputs results in a = 0, m = 1, and k = 1 as the if condition is never satisfied. But clearly, the post condition a ≥ m is violated. Below we tabulate the counterexamples invalidating the nine removed problems from the dataset: x, n = 0, 0 27

x, n = 0, 0 31

x, n = 0, 0 32

x, n = 0, 0 61 c, n = 0, 1 62 c, n = 0, 1 72 c, y = 0, 128 75 c, y = 0, 128 106 a, m, k = 0, 1, 0

H POLYNOMIAL INVARIANTS:

Here we provide results and an example of the higher order polynomial problems; more precisely, the power summation problems in the form u = k t=0 t d for a given degree d. We found that CLN2INV was able to learn invariants for programs which computes the sum of consecutive integers, which has 10 monomial terms and a maximum degree of 2. Since CLN2INV simply uses the polynomial kernel the number of terms quickly become unwieldy. We observe that CLN2INV struggles beginning with sum of squares, which has 20 monomial terms up to degree 3. Table 4 summarizes these results.

For further illustration, we describe in detail the case where d is 3, i.e. sum of cubes.

:

https://github.com/gryan11/cln2inv

Almost everywhere indicates the function is differentiable everywhere except for a set of measure 0. For example, a Rectified Linear Unit is differentiable almost everywhere except at zero.

The Code2Inv authors originally reported solving 92 problems using the same one hour timeout. We believe that the difference may be caused by changes in the testing environment or randomized model initialization.

4 At most 6171 data points are generated for a given program in the benchmark, and 1041 data points per program on average, using the sampling strategy in §5.

Figures and Tables:

Figure 1: Example Loop Invariant inference problem.

Figure 2: Illustration of the mapping S on >, ≥, = when B = 20 and = 0.2

Figure 3: System architecture and CLN construction from SMT templates.

Figure 4: Performance evaluation.

Figure 5: Finding the loop invariant for Problem 1, which involves a disjunction of equalities

Figure 7: Ablation study comparing static vs trained models.

18: bound constraints ← bound contraints∧extract loop constraint(LC) 19: end if 20: construct template((W • vars = b)) ∧ bound constraints) 21: eq clauses ← [(W • vars = b)] 22: template len ← 1 23: while template len ≤ M ax T emplate Len do 24:

clause ∧ (W • vars = b)) ∧ bound constraints) 26: eq clauses ← [eq clauses, eq clause ∧ (W • vars = b)]

clause ∨ (W • vars = b)) ∧ bound constraints) 28: eq clauses ← [eq clauses, eq clause ∨ (W • vars = b)]

t-u-) we defined in §3.

we view S(t = u) as a function over t -u, then it reaches its only local maximum at t -u = 0, which means the equality is satisfied.G INVALID PROBLEMS FROM CODE2INV DATASETHere we provide an example which is Problem 106 in the dataset. The post-condition a ≥ m is wrong if we start from a = 0, m = 1, and k = 0. int k = 0; int a, m; assume(a <= m); while (k < 1) { if (m < a) m = a; k = k + 1; } assert(a >= m);

Time spent on each stage of CLN2INV Pipeline.

Table content: <table><tr><td/><td colspan="5">Preprocessing Sampling Template Gen. CLN Training Checking</td></tr><tr><td>Avg. Time</td><td>5ms</td><td>2ms</td><td>4ms</td><td>0.5s</td><td>0.6s</td></tr><tr><td>Max Time</td><td>18ms</td><td>12ms</td><td>8ms</td><td>7.2s</td><td>5.3s</td></tr></table>

Results and summary statistics for performance evaluation.

Table content: <table><tr><td>Method</td><td colspan="4">Number Solved Avg Time (s) Avg Z3 Calls Time/Z3 Call (s)</td></tr><tr><td>Code2Inv</td><td>90</td><td>266.71</td><td>16.62</td><td>50.89</td></tr><tr><td>LoopInvGen</td><td>104</td><td>45.11</td><td>3,605.43</td><td>0.08</td></tr><tr><td>CLN2INV</td><td>124</td><td>1.07</td><td>31.77</td><td>0.17</td></tr></table>

Algorithm 1 Template Generation Algorithm. Input: Pre ← precondition Post ← post-condition LC ← loop condition Max Template Len ← max template eq clauses vars ← vars in program X ← training data 1: construct template(P ost) 2: construct template(P re) 3: clauses ← extract clauses(P re, P ost, LC) 4: for (c 1 , c 2 ) in all pairs(clauses) do : end for 8: max degree ←estimate degrees(X) 9: if max degree > 1 then 10: vars ← polynomial kernel(vars, max degree) 11: end if 12: bound constraints ← () 13: for var in vars do 14: bound constraints ← bound contraints ∧ (var ≤ u var ) 15: bound constraints ← bound contraints ∧ (var ≥ l var ) 16: end for 17: if is single constraint(LC) then

Table content: <table><tr><td>5:</td><td>construct template(c1 ∧ c2)</td></tr><tr><td>6:</td><td>construct template(c1 ∨ c2)</td></tr></table>

Invalid problems from Code2Inv dataset

Table content: <table><tr><td>Problem Counterexample starting state</td></tr><tr><td>26</td></tr></table>

Peer review (iclr2020):
The domain is loop invariant detection, in the static program analysis space. Loop invariants hold before, during, and after loop execution, and can be useful for compiler optimizations and/or correctness checking. The paper explains Basic Fuzzy Logic and then uses it to introduce Continuous Satisfiability Modulo Theories, including proposed continuous mappings for inequalities (>, >=), negations, equalities, and requirements of t-norms to be useful for the relaxated optimization proposed. This Continuous Logic Network is then optimized to provide invariant proposals to Z3, an SMT solver. The whole system is used to solve the entire Code2Inv benchmark set, in substantially faster time and with fewer proposals to Z3 than comparable previous approaches. Ablations are provided which study the t-norm used (3 options considered), and another which uses heuristics only with no training/optimization to make static proposals to Z3. On the whole, I like the presentation and the thinking here, and think it will be interesting to folks in the field, possibly spurring on further thinking in compilers, program synthesis, constrained optimization, etc, so recommend accepting. Relaxed representations of satisfiability problems seems like something people have thought about in OR for some time, so I wonder if there is a missing part of the literature survey. A cursory glance turns up https://openreview.net/forum?id=BJxgz2R9t7 Interestingly, the heuristics do quite well, which calls into question how hard the dataset is, and how competitive the preceding works really were. Since these heuristics seem to be an important contributor to this approach, I think they deserve further discussion in the appendix, and/or source code should be released. 9 problems from the dataset are rejected as invalid. Please identify these in an appendix, and provide the counterexamples. The dataset used here is quite small, and it seems like only ~30 of the problems are *hard* in requiring beyond-heuristic complexity. Couldn*t the SyGuS tools be used to generate a much larger test set? In fig 2, the model (x) doesn*t match the template/invariant /.