Algorithm Search⌘K

Algorithmresearch

Reluplex

Also called simplex with ReLU splitting.

Extends the simplex method with lazy case splits on ReLU constraints to verify properties of ReLU networks exactly.

Time
O(2^R s) worst
Space
O(R m n) extra
Where
R = the number of ReLU units; m = the number of rows of the tableau; n = the number of variables; s = the cost of one run of the simplex procedure
Properties
deterministicexactofflinerecursive
Origin
Guy Katz, Clark Barrett, David L. Dill, Kyle Julian, Mykel J. Kochenderfer, 2017

Reluplex decides exactly whether a ReLU network has an input in a given region whose output satisfies a given linear condition. It writes the network as a set of linear equations over real variables, with bounds on the variables and one pair of variables (b,f)(b, f) for each ReLU, tied by the constraint f=max⁡(0,b)f = \max(0, b). It then runs the simplex procedure for SMT on the linear part and treats the ReLU pairs lazily: a broken pair is first repaired by changing one of its two variables, and only a pair that keeps breaking is split into its two linear phases, b≤0,f=0b \le 0, f = 0 and b≥0,f=bb \ge 0, f = b. The answer is SAT with a concrete input, which is a counterexample, or UNSAT, which is a proof. Katz et al. (2017) built it to verify networks of an aircraft collision avoidance system, and their paper also shows that the problem is NP-complete, so the worst case is exponential.

Threat model. Reluplex is a defense, a verifier, so the threat model is the one that the proof covers. For robustness the goal can be untargeted or targeted, as one query is asked for each other label. The knowledge is unlimited: the proof holds against a white-box attacker. The capability is any change at test time within the region of the query, for example B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d.

In plain words

A ReLU network is a chain of weighted sums and of units that turn negative numbers into zero. Without those units, the question "can some allowed input push the wrong class above the right one?" is a set of linear inequalities, and the simplex method answers it.

Each unit is a fork with two linear roads: off (input negative, output zero) or on (output equals input). Trying all roads of all units is too slow. Reluplex first solves the linear part while it ignores the forks, then fixes the units that disagree one at a time. Only when a unit keeps going wrong does it try both roads, one after the other.

If some road gives a solution, that solution is a real input that breaks the property. If every road fails, no such input exists.

The problem

A query has real variables x1,…,xnx_1, \dots, x_n, a set of linear equations, a lower bound ljl_j and an upper bound uju_j for each variable (each may be absent), and a set RR of pairs (b,f)(b, f) with f=max⁡(0,b)f = \max(0, b). The question is whether some assignment meets all of them.

A network property becomes a query as follows. One variable is the constant 1, the inputs get the bounds of the region, each hidden unit gets a variable bb for its weighted sum (one equation) and a variable ff with f≥0f \ge 0 for its output, and one more variable is the linear output condition, such as zj−zyz_j - z_y, with the bound ≥0\ge 0. The network is robust at xx for label yy when the query is UNSAT for every j≠yj \ne y. This is the neural network verification problem for ReLU networks.

The algorithm

The procedure keeps a tableau, in which each basic variable is a linear combination of the non-basic variables, and an assignment β\beta that meets every equation at all times. It changes β\beta with the operations of simplex for SMT: UPDATE sets a non-basic variable and changes the basic variables to match, and PIVOT-AND-UPDATE moves a basic variable to a value through a non-basic variable of its row and then swaps the two.

  1. RELUPLEX(T, l, u, β, R, τ) ▷ tableau T, bounds l and u, pairs R
  2. 1repairs[p] ← 0 for every pair p in R
  3. 2loop
  4. 3if a non-basic x_j is out of its bounds then
  5. 4UPDATE(x_j, the nearest bound)
  6. 5else if a basic x_i is out of its bounds then ▷ the least such i
  7. 6x_j ← the least non-basic of the row of x_i that can move x_i toward its bound
  8. 7if there is no such x_j then return UNSAT
  9. 8PIVOT-AND-UPDATE(x_i, x_j, the violated bound)
  10. 9else if some pair p = (b, f) in R has β(f) != max(0, β(b)) then
  11. 10if repairs[p] >= τ then return SPLIT(T, l, u, β, R, τ, p)
  12. 11repairs[p] ← repairs[p] + 1
  13. 12if f and b are both basic then pivot f with a non-basic, non-fixed variable of its row
  14. 13if f is non-basic then UPDATE(f, max(0, β(b))) else UPDATE(b, β(f))
  15. 14else return SAT, β
  16. SPLIT(T, l, u, β, R, τ, p = (b, f))
  17. 15result ← RELUPLEX with u(b) ← min(u(b), 0), l(f) ← u(f) ← 0, and R - {p}
  18. 16if result is SAT then return result
  19. 17return RELUPLEX with l(b) ← max(l(b), 0), a new row e = f - b with l(e) = u(e) = 0, and R - {p}

Lines L3 to L8 are the simplex procedure with Bland's rule: the least index is chosen both for the variable to fix (line L5) and for the variable to pivot with (line L6). A basic variable that cannot move is a proof that the linear part has no solution (line L7). Lines L9 to L13 repair one broken ReLU pair by moving ff to max⁡(0,b)\max(0, b) or bb to ff, after a pivot if both are basic (line L12). A repair can break a bound, so the loop goes back to the simplex steps. Line L10 stops the repairs of a pair after τ\tau tries and splits it: line L15 tries the inactive phase and line L17 the active phase, each a purely linear constraint. The returned β\beta restricted to the inputs is the counterexample.

Example

Take the network of the interval bound propagation page: h=relu(W1x+b1)h = \mathrm{relu}(W_1 x + b_1) with b(1)=2x1−x2b^{(1)} = 2x_1 - x_2 and b(2)=x1−2x2+0.5b^{(2)} = x_1 - 2x_2 + 0.5, and the logits z0=h1−h2+1z_0 = h_1 - h_2 + 1, z1=−2h1+2h2z_1 = -2h_1 + 2h_2. At x=(0.5,0.5)x = (0.5, 0.5) the label is 00. To verify robustness on [0.25,0.75]2[0.25, 0.75]^2, Reluplex asks for an input with z1−z0=−3f1+3f2−1≥0z_1 - z_0 = -3 f_1 + 3 f_2 - 1 \ge 0, with the pairs f1=max⁡(0,b(1))f_1 = \max(0, b^{(1)}) and f2=max⁡(0,b(2))f_2 = \max(0, b^{(2)}).

The first simplex steps (lines L5 to L8) raise f2f_2 to 1/31/3 to meet the output bound, which breaks the second pair, since b(2)=0.25b^{(2)} = 0.25 at the start point. The repairs of lines L11 to L13 and the simplex steps then undo each other, and after τ=5\tau = 5 repairs line L10 splits the first pair, and later the second one. The search ends in four leaves, each a linear program:

leaf phase of unit 1 phase of unit 2 output z1−z0z_1 - z_0 on the leaf reason for UNSAT (line L7)
1 off, 2x1≤x22x_1 \le x_2 off −1-1 the output row is fixed at −1<0-1 < 0
2 off, 2x1≤x22x_1 \le x_2 on 3b(2)−13 b^{(2)} - 1 b(2)≤0.5−3x1<0b^{(2)} \le 0.5 - 3x_1 < 0, so b(2)≥0b^{(2)} \ge 0 fails
3 on off −3b(1)−1-3 b^{(1)} - 1 b(1)≥0b^{(1)} \ge 0 gives an output ≤−1\le -1
4 on on 0.5−3(x1+x2)0.5 - 3(x_1 + x_2) x1+x2≥0.5x_1 + x_2 \ge 0.5 gives an output ≤−1\le -1

Every leaf is UNSAT, so the answer is UNSAT: no input of the box changes the label. Interval bounds fail on this box, and linear bounds succeed with the lower bound 0.250.25 on z0−z1z_0 - z_1; the true minimum is 11, which leaf 4 reaches at x=(0.25,0.25)x = (0.25, 0.25). On the larger box [1/12,11/12]2[1/12, 11/12]^2, for ϵ=5/12\epsilon = 5/12, the first simplex steps already end at line L14 with SAT and the input x=(1/12,1/12)x = (1/12, 1/12), where both logits are 2/32/3. So 5/125/12 is the exact robust radius of this point.

Correctness

Theorem (sound and complete). For τ≥1\tau \ge 1, RELUPLEX terminates. If it returns SAT, β\beta meets every equation, every bound and every pair of the query. If it returns UNSAT, the query has no solution.

The key facts are as follows. Every operation keeps the equations true, so at line L14 the assignment meets equations, bounds and pairs. Line L7 is reached only when every non-basic variable is within its bounds (line L3) and each one that could help xix_i is at its limit; then the row gives a bound on xix_i that every solution must meet, and it is violated. Every solution of the query satisfies one of the two phases of a pair, and each phase is exactly what line L15 or line L17 adds, so UNSAT in both branches is UNSAT for the query. For termination, each simplex phase ends by Bland's rule, as in simplex for SMT, each pair is repaired at most τ\tau times before a split, and each split removes one pair. The full proof is in proofs/correctness.md.

Proof: Reluplex terminates, a SAT answer is a solution, and an UNSAT answer is a prooffull

A query has variables x1,…,xnx_1, \dots, x_n, a tableau TT in which each basic variable xix_i equals ∑jaijxj\sum_j a_{ij} x_j over the non-basic variables, bounds lj≤xj≤ujl_j \le x_j \le u_j (either may be absent), and a set RR of pairs (b,f)(b, f) with the constraint f=max⁡(0,b)f = \max(0, b). A solution is an assignment that meets all equations, bounds and pairs. Arithmetic is exact. We assume that the start assignment β\beta meets every equation, which holds for the encoding of the page, since every basic variable is computed from its row.

Lemma 1 (the equations stay true). Every step of RELUPLEX and SPLIT keeps β\beta a solution of all equations of the current tableau, and the tableaux before and after a pivot have the same solutions.

Proof. UPDATE(xj,v)(x_j, v) changes the non-basic xjx_j by δ=v−β(xj)\delta = v - \beta(x_j) and each basic xix_i by aijδa_{ij}\delta, so each row xi=∑jaijxjx_i = \sum_j a_{ij} x_j stays true. PIVOT-AND-UPDATE first does the same with θ=(v−β(xi))/aij\theta = (v - \beta(x_i))/a_{ij} for the non-basic xjx_j, then pivots. A pivot solves the row of xix_i for xjx_j (possible because aij≠0a_{ij} \ne 0) and substitutes the result into the other rows. These are equivalent rewritings of the same linear system, so they have the same solutions and β\beta stays one. Line L17 adds a new basic variable ee whose row is the row of ff minus the row of bb, written in the current non-basic variables, and sets β(e)\beta(e) from it, so the new row holds. Changes of bounds do not touch the equations. □\square

Lemma 2 (SAT is a solution). If RELUPLEX returns at line L14, β\beta is a solution of the current query. If SPLIT returns SAT, the returned assignment, restricted to the variables of its input query, is a solution of that query.

Proof. Line L14 is reached only when no non-basic variable (line L3) and no basic variable (line L5) is out of its bounds and no pair is broken (line L9). With Lemma 1, β\beta meets all equations, all bounds and all pairs of RR.

For SPLIT, let p=(b,f)p = (b, f). The branch of line L15 has the bounds of the input query, made tighter, and the pairs R−{p}R - \{p\}. A solution of it also has b≤0b \le 0 and f=0f = 0, so f=max⁡(0,b)f = \max(0, b) and pp holds as well. The branch of line L17 adds the variable e=f−be = f - b fixed to 00, and the bound b≥0b \ge 0; a solution of it has f=b≥0f = b \ge 0, so again f=max⁡(0,b)f = \max(0, b). In both cases the other equations and bounds of the input query are among those of the branch, so dropping ee leaves a solution of the input query. By induction on the depth of the recursion, every SAT answer is a solution of the query at the top. □\square

Lemma 3 (the simplex failure is a proof). If line L7 returns UNSAT, the current query has no solution, not even without the pairs.

Proof. Line L5 is reached only when every non-basic variable is within its bounds, since line L3 comes first. Say that the basic xix_i is below its lower bound, β(xi)<li\beta(x_i) < l_i (the other case is symmetric). No candidate exists at line L6, so every non-basic xjx_j with aij>0a_{ij} > 0 has β(xj)=uj\beta(x_j) = u_j (it has an upper bound and is at it), and every non-basic xjx_j with aij<0a_{ij} < 0 has β(xj)=lj\beta(x_j) = l_j. Take any assignment γ\gamma that meets the bounds and the equations. Then

γ(xi)=∑jaijγ(xj)≤∑aij>0aijuj+∑aij<0aijlj=∑jaijβ(xj)=β(xi)<li,\gamma(x_i) = \sum_j a_{ij}\gamma(x_j) \le \sum_{a_{ij} > 0} a_{ij} u_j + \sum_{a_{ij} < 0} a_{ij} l_j = \sum_j a_{ij}\beta(x_j) = \beta(x_i) < l_i,

so γ\gamma breaks the lower bound of xix_i. Hence no assignment meets the equations and the bounds. □\square

Lemma 4 (the split covers every solution). Let p=(b,f)∈Rp = (b, f) \in R. Every solution of the query is a solution of the branch of line L15 or, after setting e=f−be = f - b, of the branch of line L17.

Proof. Let γ\gamma be a solution, so γ(f)=max⁡(0,γ(b))\gamma(f) = \max(0, \gamma(b)). If γ(b)≤0\gamma(b) \le 0, then γ(f)=0\gamma(f) = 0, so γ\gamma meets b≤0b \le 0 and 0≤f≤00 \le f \le 0 together with the old bounds, which are the bounds of line L15; it meets the pairs R−{p}R - \{p\} and the equations. If γ(b)>0\gamma(b) > 0, then γ(f)=γ(b)\gamma(f) = \gamma(b), so γ(e)=0\gamma(e) = 0 and γ\gamma meets b≥0b \ge 0 and 0≤e≤00 \le e \le 0, the bounds of line L17. The row of ee is the row of ff minus the row of bb, so it holds for any assignment that meets the other equations. □\square

Lemma 5 (termination). For τ≥1\tau \ge 1, every call of RELUPLEX returns.

Proof. By induction on ∣R∣|R|. Consider one call. Between two executions of lines L9 to L13 (or before the first one), the loop runs lines L3 to L8 only. Line L4 puts one non-basic variable on a bound, and lines L5 to L8 never move a non-basic variable out of its bounds: PIVOT-AND-UPDATE puts xix_i, which becomes non-basic, on a bound, and changes no other non-basic variable. So line L4 runs at most nn times in a row, after which lines L5 to L8 are the simplex procedure of Dutertre and de Moura with Bland's rule, the least index both for the variable to fix and for the variable to pivot with. That procedure terminates (the theorem of the simplex for SMT page), so this stretch of the loop ends at line L7, at line L14, or at line L9.

Each time line L11 runs, the counter of one pair grows by one, and line L10 splits as soon as a counter reaches τ\tau. Lines L12 and L13 run only after line L11. So line L11 runs at most τ∣R∣\tau |R| times in one call, and after that the call returns at line L7, line L10 or line L14. A split at line L10 makes two calls, each with ∣R∣−1|R| - 1 pairs, which return by the induction hypothesis (with R=∅R = \emptyset, line L9 never fires and the call is a plain simplex run, which terminates). □\square

Theorem. For τ≥1\tau \ge 1, RELUPLEX terminates. If it returns SAT, the assignment is a solution of the query. If it returns UNSAT, the query has no solution. So for a network query, SAT gives an input in the region that meets the output condition, and UNSAT proves that no such input exists.

Proof. Termination is Lemma 5, and the SAT case is Lemma 2. For UNSAT, use induction on the depth of the recursion. An UNSAT answer comes from line L7, which is a proof by Lemma 3 (a query without solutions of its linear part has no solutions at all), or from line L10, where both branches of SPLIT returned UNSAT. By the induction hypothesis neither branch has a solution, so by Lemma 4 the query has none. Lemma 1 shows that the tableau of each call has the same solutions as the query it was given. For a network query, the encoding has one equation per hidden unit and one for the output, the input bounds of the region, and one pair per ReLU, so its solutions are exactly the inputs of the region that meet the output condition, together with the values of the hidden units. ■\blacksquare

Complexity

  • Time. The problem is NP-complete (Katz et al. 2017), so no polynomial method is expected. The split tree of lines L15 to L17 has at most 2R2^R leaves, each a run of the simplex procedure, and the simplex procedure with Bland's rule can itself take exponentially many pivots in the worst case, though it is fast in practice. Lazy splitting means that the tree is often much smaller than 2R2^R: a pair that the repairs can fix is never split.
  • Space. Each level of the recursion keeps a copy of the tableau, of size O(mn)O(m n) in a dense form, and the depth is at most RR, so O(Rmn)O(R m n).
  • Pivot cost. One pivot costs O(mn)O(m n) with a dense tableau.

Properties

  • Exact (complete and sound). SAT comes with a real counterexample and UNSAT is a proof, both in exact arithmetic (a theorem).
  • Exponential worst case. The verification problem is NP-complete, so a large network can take a very long time. Exact verifiers reach much smaller networks than the incomplete bounds of linear bound propagation do.
  • Exact robust accuracy. On the points it finishes, it gives the true answer, so it closes the gap between an attack (an upper bound on robust accuracy) and an incomplete certificate (a lower bound).
  • Lazy splits. A pair is split only after τ\tau failed repairs. A stable unit, whose bounds already fix its phase, is never split.

Variants and improvements

  • Bound tightening. Katz et al. derive tighter bounds of bb and ff from the rows of the tableau during the search. A pair whose bounds fix its phase becomes a linear constraint without a split. Interval bounds, as in interval bound propagation, give a cheap start.
  • Conflict analysis. When a branch is UNSAT, the solver can find which splits caused it and skip other branches with the same cause, as in CDCL SAT solvers.
  • Marabou. The successor tool of the same group (Katz et al. 2019) adds more activation functions, splitting heuristics, parallel search and other improvements.
  • Mixed integer programming. The same problem can be written as a mixed integer program with one binary variable per unstable ReLU, and solved with a general MIP solver.
  • Branch and bound with linear bounds. Modern complete verifiers split ReLU phases in a search tree and prune each node with linear bound propagation instead of a full simplex run.

When to use it

Use Reluplex, or one of its successors, when an exact answer is needed for a small network: a safety property of a controller, a proof that a fixed point is robust, or a ground truth for testing an incomplete verifier. For large networks, use an incomplete bound such as linear bound propagation or a probabilistic certificate such as randomized smoothing, and accept that some points stay unknown.

Pitfalls

  • Pivoting with the constant. If line L12 pivots ff with a fixed variable, such as the variable that holds the constant 1, the following UPDATE moves a fixed variable off its value. The result is still correct, because the simplex steps move it back, but the repairs make no progress. Pivot only with a variable whose bounds are not equal.
  • A split that forgets f≥0f \ge 0. Line L15 must fix ff to 00, not only bound it above by 00. If ff has no lower bound, a branch with f<0f < 0 and b≤0b \le 0 meets the new bounds but breaks f=max⁡(0,b)f = \max(0, b).
  • Floating point. The theorem holds in exact arithmetic. A solver on floats can report UNSAT wrongly after rounding; the tests of this page use exact rational numbers, and real tools check SAT answers by a forward pass.
  • No bound on the repairs. Without line L10 the repairs and the simplex steps can undo each other forever, as in the example at ϵ=0.25\epsilon = 0.25.
  • A strict condition. A property zj−zy>0z_j - z_y > 0 needs a strict bound. The page asks for zj−zy≥0z_j - z_y \ge 0 instead, so a tie, as at ϵ=5/12\epsilon = 5/12, counts as a counterexample. This matches a certificate that asks for a strictly positive margin.

Implementations

The code of this page is an abstract model on synthetic data. The verifier runs only on small ReLU networks that the tests build from a fixed seed, with weights from mlkit.tiny_relu_net or a seeded generator rounded to multiples of 1/81/8, and it works in exact rational arithmetic (fractions.Fraction). It never reads real data or touches a real system. The tests check the example (UNSAT at ϵ=1/4\epsilon = 1/4 and the radius 5/125/12), small linear programs, a single ReLU pair, and SAT or UNSAT on 500 random queries against the exact maximum from an enumeration of all activation patterns. They also check that each SAT answer is a true counterexample and meets every equation and pair.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

mlkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small vector tools, synthetic data and two tiny models for the adversarial machine learning pages.

Vectors are lists of floats. Every model here is synthetic: it is built from a seeded
random.Random and never from real data. The helper holds no attack loop, no
certification and no defense; those live in the slug files of the pages.
"""

import math
import random
from typing import Callable, Sequence

Vector = list[float]
Matrix = list[list[float]]
Net = dict[str, list]
Data = list[tuple[Vector, int]]


def dot(u: Sequence[float], v: Sequence[float]) -> float:
    """Inner product of two vectors of the same length. Cost O(d)."""
    return math.fsum(a * b for a, b in zip(u, v, strict=True))


def add(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise sum u + v. Cost O(d)."""
    return [a + b for a, b in zip(u, v, strict=True)]


def sub(u: Sequence[float], v: Sequence[float]) -> Vector:
    """Coordinatewise difference u - v. Cost O(d)."""
    return [a - b for a, b in zip(u, v, strict=True)]


def scale(c: float, v: Sequence[float]) -> Vector:
    """The vector c v. Cost O(d)."""
    return [c * a for a in v]


def norm1(v: Sequence[float]) -> float:
    """The l1 norm, the sum of |v_i|. Cost O(d)."""
    return math.fsum(abs(a) for a in v)


def norm2(v: Sequence[float]) -> float:
    """The Euclidean norm. Cost O(d)."""
    return math.sqrt(math.fsum(a * a for a in v))


def norminf(v: Sequence[float]) -> float:
    """The l_infinity norm, max |v_i|, and 0 for the empty vector. Cost O(d)."""
    return max((abs(a) for a in v), default=0.0)


def project_l2(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l2 ball of the given center and radius >= 0.

    A point inside the ball is returned unchanged; a point outside is moved along the
    segment to the center until it is on the sphere. Cost O(d).
    """
    diff = sub(v, center)
    r = norm2(diff)
    if r <= radius:
        return list(v)
    return add(center, scale(radius / r, diff))


def project_linf(v: Sequence[float], center: Sequence[float], radius: float) -> Vector:
    """Euclidean projection of v onto the l_infinity ball: clip each coordinate to [c_i - r, c_i + r]. Cost O(d)."""
    return [min(max(a, c - radius), c + radius) for a, c in zip(v, center, strict=True)]


def clip01(v: Sequence[float]) -> Vector:
    """Euclidean projection onto the box [0, 1]^d. Cost O(d)."""
    return [min(max(a, 0.0), 1.0) for a in v]


def make_blobs(rng: random.Random, n: int, d: int, centers: Sequence[Sequence[float]], sigma: float) -> Data:
    """n synthetic points in R^d from Gaussian blobs N(center, sigma^2 I).

    Point i gets the label i mod len(centers) and is drawn around that center, so the
    classes are balanced. The points are not clipped. Cost O(n d) and n d draws of rng.
    """
    for c in centers:
        if len(c) != d:
            raise ValueError("each center must have d coordinates")
    data: Data = []
    for i in range(n):
        label = i % len(centers)
        x = [c + rng.gauss(0.0, sigma) for c in centers[label]]
        data.append((x, label))
    return data


def sigmoid(t: float) -> float:
    """The logistic function 1 / (1 + e^(-t)), computed without overflow. Cost O(1)."""
    if t >= 0:
        return 1.0 / (1.0 + math.exp(-t))
    e = math.exp(t)
    return e / (1.0 + e)


def _softplus(t: float) -> float:
    """ln(1 + e^t) without overflow."""
    return max(t, 0.0) + math.log1p(math.exp(-abs(t)))


def logistic_loss(w: Sequence[float], b: float, x: Sequence[float], y: int) -> float:
    """Logistic loss of the linear model z = w.x + b on a label y in {0, 1}.

    The loss is ln(1 + e^(-s z)) with s = 2 y - 1. Cost O(d).
    """
    s = 2 * y - 1
    return _softplus(-s * (dot(w, x) + b))


def grad_x_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> Vector:
    """Gradient of logistic_loss in the input x: (sigmoid(z) - y) w. Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, w)


def grad_w_logistic(w: Sequence[float], b: float, x: Sequence[float], y: int) -> tuple[Vector, float]:
    """Gradient of logistic_loss in the parameters: ((sigmoid(z) - y) x, sigmoid(z) - y). Cost O(d)."""
    g = sigmoid(dot(w, x) + b) - y
    return scale(g, x), g


def train_logistic(data: Data, steps: int, lr: float, l2: float) -> tuple[Vector, float]:
    """Full-batch gradient descent on the mean logistic loss plus (l2 / 2) ||w||^2.

    Labels are in {0, 1}. The weights start at zero, so the result is deterministic.
    The bias has no penalty. Returns (w, b). Cost O(steps n d).
    """
    d = len(data[0][0])
    n = len(data)
    w = [0.0] * d
    b = 0.0
    for _ in range(steps):
        gw = [0.0] * d
        gb = 0.0
        for x, y in data:
            g = sigmoid(dot(w, x) + b) - y
            for j in range(d):
                gw[j] += g * x[j]
            gb += g
        w = [w[j] - lr * (gw[j] / n + l2 * w[j]) for j in range(d)]
        b -= lr * gb / n
    return w, b


def tiny_relu_net(rng: random.Random, d: int, h: int, k: int) -> Net:
    """A fixed-seed two-layer ReLU network with d inputs, h hidden units and k logits.

    The weights are drawn from N(0, 1/d) in the first layer and N(0, 1/h) in the second,
    and the biases from N(0, 0.01). The dict has the keys W1 (h rows of d), b1 (h),
    W2 (k rows of h) and b2 (k). Cost O(h d + k h).
    """
    s1, s2 = 1.0 / math.sqrt(d), 1.0 / math.sqrt(h)
    return {
        "W1": [[rng.gauss(0.0, s1) for _ in range(d)] for _ in range(h)],
        "b1": [rng.gauss(0.0, 0.1) for _ in range(h)],
        "W2": [[rng.gauss(0.0, s2) for _ in range(h)] for _ in range(k)],
        "b2": [rng.gauss(0.0, 0.1) for _ in range(k)],
    }


def _hidden(net: Net, x: Sequence[float]) -> tuple[Vector, Vector]:
    """Pre-activations and activations of the hidden layer."""
    pre = [dot(row, x) + bi for row, bi in zip(net["W1"], net["b1"], strict=True)]
    return pre, [max(a, 0.0) for a in pre]


def forward(net: Net, x: Sequence[float]) -> Vector:
    """Logits z(x) = W2 relu(W1 x + b1) + b2 of a tiny_relu_net. Cost O(h d + k h)."""
    _, act = _hidden(net, x)
    return [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]


def argmax(z: Sequence[float]) -> int:
    """The first index of a largest entry. Cost O(k)."""
    best = 0
    for i in range(1, len(z)):
        if z[i] > z[best]:
            best = i
    return best


def softmax(z: Sequence[float]) -> Vector:
    """The softmax of a logit vector, shifted by the maximum to avoid overflow. Cost O(k)."""
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = math.fsum(e)
    return [a / s for a in e]


def cross_entropy(z: Sequence[float], label: int) -> float:
    """Cross-entropy loss -ln softmax(z)[label], computed as logsumexp(z) - z[label]. Cost O(k)."""
    m = max(z)
    return m + math.log(math.fsum(math.exp(a - m) for a in z)) - z[label]


def logits_jacobian(net: Net, x: Sequence[float]) -> Matrix:
    """The k by d Jacobian of the logits in the input, W2 diag(relu'(pre)) W1.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(k h d).
    """
    pre, _ = _hidden(net, x)
    d = len(x)
    rows = []
    for w2 in net["W2"]:
        row = [0.0] * d
        for i, a in enumerate(pre):
            if a > 0 and w2[i] != 0.0:
                c = w2[i]
                w1 = net["W1"][i]
                for j in range(d):
                    row[j] += c * w1[j]
        rows.append(row)
    return rows


def input_gradient(net: Net, x: Sequence[float], label: int) -> Vector:
    """Gradient in x of cross_entropy(forward(net, x), label), by backpropagation.

    The derivative of the ReLU is taken as 0 at a pre-activation of exactly 0.
    Cost O(h d + k h).
    """
    pre, act = _hidden(net, x)
    z = [dot(row, act) + bi for row, bi in zip(net["W2"], net["b2"], strict=True)]
    p = softmax(z)
    p[label] -= 1.0
    back = [0.0] * len(pre)
    for c, row in zip(p, net["W2"], strict=True):
        for i in range(len(pre)):
            back[i] += c * row[i]
    g = [0.0] * len(x)
    for i, a in enumerate(pre):
        if a > 0:
            w1 = net["W1"][i]
            for j in range(len(x)):
                g[j] += back[i] * w1[j]
    return g


def accuracy(predict: Callable[[Vector], int], data: Data) -> float:
    """Fraction of the pairs (x, y) of data with predict(x) == y. Cost: n calls of predict."""
    if not data:
        return 0.0
    return sum(1 for x, y in data if predict(x) == y) / len(data)
reluplex.py 246 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reluplex/. The authors are listed in prov/J93TRS.jsonl.

"""Reluplex: the simplex method of Dutertre and de Moura, extended with ReLU pairs.

The query is a conjunction of linear equations (the tableau), bounds on the variables
and ReLU pairs f = max(0, b). The procedure keeps an assignment that meets every
equation. Simplex steps repair bounds, repair steps repair ReLU pairs, and a pair that
was repaired tau times is split into its two linear phases. All arithmetic is exact
(fractions.Fraction), so SAT and UNSAT answers are exact for the rational query.

The networks in the tests are synthetic networks with seeded rational weights.
"""

from fractions import Fraction
from typing import Optional, Sequence

Num = Fraction
Bound = Optional[Fraction]
Layer = tuple[Sequence[Sequence[Fraction]], Sequence[Fraction]]


class Query:
    """A tableau with bounds, an assignment and ReLU pairs.

    basic maps each basic variable to its row, a dict from non-basic variables to
    non-zero coefficients: x_i = sum of row[j] x_j. lo and hi hold the bounds (None for
    no bound) and val the assignment. pairs lists (b, f) with the constraint f = max(0, b).
    """

    def __init__(self, nvars: int) -> None:
        self.lo: list[Bound] = [None] * nvars
        self.hi: list[Bound] = [None] * nvars
        self.val: list[Num] = [Fraction(0)] * nvars
        self.basic: dict[int, dict[int, Num]] = {}
        self.pairs: list[tuple[int, int]] = []

    def copy(self) -> "Query":
        q = Query(0)
        q.lo, q.hi, q.val = list(self.lo), list(self.hi), list(self.val)
        q.basic = {i: dict(r) for i, r in self.basic.items()}
        q.pairs = list(self.pairs)
        return q

    def row_of(self, v: int) -> dict[int, Num]:
        """v as a combination of non-basic variables."""
        return dict(self.basic[v]) if v in self.basic else {v: Fraction(1)}

    def add_basic(self, row: dict[int, Num], lo: Bound, hi: Bound) -> int:
        """A new basic variable equal to the combination row of non-basic variables."""
        v = len(self.val)
        self.lo.append(lo)
        self.hi.append(hi)
        self.val.append(sum((c * self.val[j] for j, c in row.items()), Fraction(0)))
        self.basic[v] = {j: c for j, c in row.items() if c != 0}
        return v

    def below(self, v: int) -> bool:
        return self.lo[v] is not None and self.val[v] < self.lo[v]

    def above(self, v: int) -> bool:
        return self.hi[v] is not None and self.val[v] > self.hi[v]

    def update(self, j: int, v: Num) -> None:
        """Set the non-basic x_j to v and keep every equation true."""
        delta = v - self.val[j]
        for i, row in self.basic.items():
            if j in row:
                self.val[i] += row[j] * delta
        self.val[j] = v

    def pivot(self, i: int, j: int) -> None:
        """Make the basic x_i non-basic and the non-basic x_j basic. The assignment does not change."""
        row = self.basic.pop(i)
        a = row.pop(j)
        new = {k: -c / a for k, c in row.items()}
        new[i] = 1 / a
        for r in self.basic.values():
            if j in r:
                c = r.pop(j)
                for k, e in new.items():
                    s = r.get(k, Fraction(0)) + c * e
                    if s == 0:
                        r.pop(k, None)
                    else:
                        r[k] = s
        self.basic[j] = new

    def pivot_and_update(self, i: int, j: int, v: Num) -> None:
        """Move the basic x_i to v by a change of the non-basic x_j, then pivot them."""
        theta = (v - self.val[i]) / self.basic[i][j]
        self.val[i] = v
        self.val[j] += theta
        for k, row in self.basic.items():
            if k != i and j in row:
                self.val[k] += row[j] * theta
        self.pivot(i, j)


def relu_violated(q: Query, p: tuple[int, int]) -> bool:
    b, f = p
    return q.val[f] != max(Fraction(0), q.val[b])


def reluplex(q: Query, tau: int = 5) -> Optional[list[Num]]:
    """Decide the query. Returns a satisfying assignment, or None when there is none.

    Precondition: the assignment meets every equation of the tableau; tau >= 1.
    Simplex steps use Bland's rule (least index), so each simplex phase terminates,
    and each pair is repaired at most tau times before it is split, so the whole
    procedure terminates. Cost: exponential in the number of pairs in the worst case;
    each simplex phase can also take exponentially many pivots in the worst case.
    """
    repairs = {p: 0 for p in q.pairs}  # @line L1
    while True:  # @line L2
        nb = [j for j in range(len(q.val)) if j not in q.basic and (q.below(j) or q.above(j))]
        if nb:  # @line L3
            j = nb[0]
            q.update(j, q.lo[j] if q.below(j) else q.hi[j])  # @line L4
            continue
        bad = [i for i in sorted(q.basic) if q.below(i) or q.above(i)]
        if bad:  # @line L5
            i = bad[0]
            row = q.basic[i]
            if q.below(i):
                cand = [j for j in sorted(row) if (row[j] > 0 and (q.hi[j] is None or q.val[j] < q.hi[j]))
                        or (row[j] < 0 and (q.lo[j] is None or q.val[j] > q.lo[j]))]  # @line L6
                target = q.lo[i]
            else:
                cand = [j for j in sorted(row) if (row[j] < 0 and (q.hi[j] is None or q.val[j] < q.hi[j]))
                        or (row[j] > 0 and (q.lo[j] is None or q.val[j] > q.lo[j]))]  # @line L6
                target = q.hi[i]
            if not cand:  # @line L7
                return None  # @line L7
            q.pivot_and_update(i, cand[0], target)  # @line L8
            continue
        broken = [p for p in q.pairs if relu_violated(q, p)]
        if broken:  # @line L9
            p = broken[0]
            b, f = p
            free = [j for j in sorted(q.basic.get(f, {})) if j != b and q.lo[j] != q.hi[j]]
            if repairs[p] >= tau or (f in q.basic and b in q.basic and not free):  # @line L10
                return split(q, p, tau)  # @line L10
            repairs[p] += 1  # @line L11
            if f in q.basic and b in q.basic:  # @line L12
                q.pivot(f, free[0])  # @line L12: never with a fixed variable such as the constant
            if f not in q.basic:  # @line L13
                q.update(f, max(Fraction(0), q.val[b]))  # @line L13
            else:
                q.update(b, q.val[f])  # @line L13
            continue
        return list(q.val)  # @line L14


def split(q: Query, p: tuple[int, int], tau: int) -> Optional[list[Num]]:
    """Case split on the pair p = (b, f): first b <= 0 and f = 0, then b >= 0 and f = b.

    Every solution of the query meets one of the two phases, and in each phase the pair
    is a linear constraint, so it is removed from the list of pairs.
    """
    b, f = p
    rest = [r for r in q.pairs if r != p]
    off = q.copy()  # @line L15
    off.pairs = rest  # @line L15
    off.hi[b] = Fraction(0) if off.hi[b] is None else min(off.hi[b], Fraction(0))  # @line L15
    off.hi[f] = Fraction(0) if off.hi[f] is None else min(off.hi[f], Fraction(0))  # @line L15
    off.lo[f] = Fraction(0) if off.lo[f] is None else max(off.lo[f], Fraction(0))  # @line L15: so f = 0
    result = reluplex(off, tau)  # @line L15
    if result is not None:  # @line L16
        return result[: len(q.val)]  # @line L16
    on = q.copy()  # @line L17
    on.pairs = rest  # @line L17
    on.lo[b] = Fraction(0) if on.lo[b] is None else max(on.lo[b], Fraction(0))  # @line L17
    row = on.row_of(f)
    for j, c in on.row_of(b).items():
        row[j] = row.get(j, Fraction(0)) - c
    on.add_basic(row, Fraction(0), Fraction(0))  # @line L17: the new variable e = f - b is fixed to 0
    result = reluplex(on, tau)  # @line L17
    return None if result is None else result[: len(q.val)]  # @line L17


def encode(layers: Sequence[Layer], lower: Sequence[Fraction], upper: Sequence[Fraction],
           row: Sequence[Fraction], threshold: Fraction) -> tuple[Query, list[int]]:
    """The query: some x in [lower, upper] has row . z(x) >= threshold.

    Variable 0 is the constant 1, variables 1 .. d are the inputs, then each hidden
    unit has a pair (b, f), and the last variable is the output row . z(x).
    Returns the query and the indices of the input variables. Cost O(N) for N weights.
    """
    d = len(lower)
    nh = sum(len(w) for w, _ in layers[:-1])
    q = Query(1 + d + nh)
    q.lo[0] = q.hi[0] = Fraction(1)
    q.val[0] = Fraction(1)
    inputs = list(range(1, d + 1))
    for t, j in enumerate(inputs):
        q.lo[j], q.hi[j] = lower[t], upper[t]
        q.val[j] = lower[t]
    prev = inputs
    nxt = d + 1
    for w, bias in layers[:-1]:
        fs = []
        for wr, bi in zip(w, bias, strict=True):
            f = nxt
            nxt += 1
            q.lo[f] = Fraction(0)
            r = {0: bi}
            for c, v in zip(wr, prev, strict=True):
                r[v] = r.get(v, Fraction(0)) + c
            b = q.add_basic(r, None, None)
            q.pairs.append((b, f))
            fs.append(f)
        prev = fs
    w, bias = layers[-1]
    out = {0: sum((c * bi for c, bi in zip(row, bias, strict=True)), Fraction(0))}
    for t, v in enumerate(prev):
        out[v] = sum((c * wr[t] for c, wr in zip(row, w, strict=True)), Fraction(0))
    q.add_basic(out, threshold, None)
    return q, inputs


def exists_output_at_least(layers: Sequence[Layer], lower: Sequence[Fraction], upper: Sequence[Fraction],
                           row: Sequence[Fraction], threshold: Fraction, tau: int = 5) -> Optional[list[Fraction]]:
    """An input x in the box with row . z(x) >= threshold, or None if there is none."""
    q, inputs = encode(layers, lower, upper, row, threshold)
    sol = reluplex(q, tau)
    return None if sol is None else [sol[j] for j in inputs]


def verify_robust(layers: Sequence[Layer], x: Sequence[Fraction], y: int, epsilon: Fraction,
                  tau: int = 5) -> Optional[list[Fraction]]:
    """None if y is the only argmax on B_infinity(x, epsilon) in [0, 1]^d, else a counterexample.

    For each label j != y it asks whether some input of the box has z_j - z_y >= 0.
    """
    lower = [max(a - epsilon, Fraction(0)) for a in x]
    upper = [min(a + epsilon, Fraction(1)) for a in x]
    k = len(layers[-1][0])
    for j in range(k):
        if j == y:
            continue
        row = [Fraction(1) if t == j else Fraction(-1) if t == y else Fraction(0) for t in range(k)]
        cex = exists_output_at_least(layers, lower, upper, row, Fraction(0), tau)
        if cex is not None:
            return cex
    return None
test_reluplex.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reluplex/. The authors are listed in prov/J93TRS.jsonl.

"""Tests of Reluplex on seeded synthetic ReLU networks with rational weights only."""

import itertools
import random
from fractions import Fraction as Fr

import mlkit as m
from reluplex import Query, encode, exists_output_at_least, reluplex, verify_robust

# The network of the worked example: two inputs, two hidden ReLUs, two logits.
EXAMPLE = [([[Fr(2), Fr(-1)], [Fr(1), Fr(-2)]], [Fr(0), Fr(1, 2)]), ([[Fr(1), Fr(-1)], [Fr(-2), Fr(2)]], [Fr(1), Fr(0)])]


def forward(layers, x):
    a = list(x)
    for k, (w, b) in enumerate(layers):
        a = [sum((wi * ai for wi, ai in zip(row, a)), Fr(0)) + bi for row, bi in zip(w, b)]
        if k < len(layers) - 1:
            a = [max(v, Fr(0)) for v in a]
    return a


def exact_max(layers, lower, upper, row):
    """Exact max of row . z(x) over a 2-dimensional box, in rational arithmetic.

    The oracle enumerates every activation pattern. On the region of one pattern the
    network is affine, so the maximum over the region is at a vertex; each vertex is
    the meet of two constraint lines, solved by Cramer's rule.
    """
    d = 2
    sizes = [len(w) for w, _ in layers[:-1]]
    best = None
    for pat in itertools.product([0, 1], repeat=sum(sizes)):
        cons = [([Fr(1), Fr(0)], -lower[0]), ([Fr(-1), Fr(0)], upper[0]), ([Fr(0), Fr(1)], -lower[1]), ([Fr(0), Fr(-1)], upper[1])]
        a = [[Fr(1), Fr(0)], [Fr(0), Fr(1)]]
        c = [Fr(0), Fr(0)]
        p = 0
        for k, (w, b) in enumerate(layers):
            a2 = [[sum((w[i][t] * a[t][j] for t in range(len(a))), Fr(0)) for j in range(d)] for i in range(len(w))]
            c2 = [sum((w[i][t] * c[t] for t in range(len(c))), Fr(0)) + b[i] for i in range(len(w))]
            if k < len(layers) - 1:
                for i in range(len(w)):
                    if pat[p]:
                        cons.append((a2[i], c2[i]))
                    else:
                        cons.append(([-v for v in a2[i]], -c2[i]))
                        a2[i], c2[i] = [Fr(0)] * d, Fr(0)
                    p += 1
            a, c = a2, c2
        g = [sum((row[i] * a[i][j] for i in range(len(row))), Fr(0)) for j in range(d)]
        g0 = sum((row[i] * c[i] for i in range(len(row))), Fr(0))
        for (r1, c1), (r2, c2v) in itertools.combinations(cons, 2):
            det = r1[0] * r2[1] - r1[1] * r2[0]
            if det == 0:
                continue
            x0 = (-c1 * r2[1] + r1[1] * c2v) / det
            x1 = (-r1[0] * c2v + c1 * r2[0]) / det
            if all(r[0] * x0 + r[1] * x1 + cc >= 0 for r, cc in cons):
                v = g[0] * x0 + g[1] * x1 + g0
                best = v if best is None else max(best, v)
    return best


def rational_net(rng: random.Random, sizes: list[int]) -> list:
    """A seeded network from mlkit, with each weight rounded to a multiple of 1/8."""
    if len(sizes) == 3:
        net = m.tiny_relu_net(rng, sizes[0], sizes[1], sizes[2])
        raw = [(net["W1"], net["b1"]), (net["W2"], net["b2"])]
    else:
        raw = [([[rng.uniform(-2, 2) for _ in range(a)] for _ in range(b)], [rng.uniform(-1, 1) for _ in range(b)])
               for a, b in zip(sizes, sizes[1:])]
    return [([[Fr(round(v * 8), 8) for v in r] for r in w], [Fr(round(v * 8), 8) for v in b]) for w, b in raw]


def test_example_is_robust_at_one_quarter():
    x = [Fr(1, 2), Fr(1, 2)]
    assert forward(EXAMPLE, x) == [Fr(3, 2), Fr(-1)]
    assert verify_robust(EXAMPLE, x, 0, Fr(1, 4)) is None
    lower, upper = [Fr(1, 4)] * 2, [Fr(3, 4)] * 2
    assert exact_max(EXAMPLE, lower, upper, [Fr(-1), Fr(1)]) == Fr(-1)


def test_example_radius_is_5_over_12():
    x = [Fr(1, 2), Fr(1, 2)]
    assert verify_robust(EXAMPLE, x, 0, Fr(5, 12) - Fr(1, 1000)) is None
    cex = verify_robust(EXAMPLE, x, 0, Fr(5, 12))
    assert cex is not None
    z = forward(EXAMPLE, cex)
    assert z[1] >= z[0]
    assert all(abs(a - Fr(1, 2)) <= Fr(5, 12) for a in cex)


def test_plain_linear_program():
    # x1 + x2 >= 3 with 0 <= x1, x2 <= 1 has no solution; >= 2 has one.
    for t, sat in ((Fr(3), False), (Fr(2), True)):
        q = Query(3)
        q.lo[0] = q.hi[0] = q.val[0] = Fr(1)
        for j in (1, 2):
            q.lo[j], q.hi[j] = Fr(0), Fr(1)
        s = q.add_basic({1: Fr(1), 2: Fr(1)}, t, None)
        sol = reluplex(q)
        assert (sol is not None) == sat
        if sol is not None:
            assert sol[s] == sol[1] + sol[2] >= t


def test_single_relu_pair():
    # f = max(0, b) with b = x - 1/2, x in [0, 1]: f >= 1/2 holds only at x = 1.
    for t, sat in ((Fr(1, 2), True), (Fr(1, 2) + Fr(1, 64), False)):
        layers = [([[Fr(1)]], [Fr(-1, 2)]), ([[Fr(1)]], [Fr(0)])]
        q, inputs = encode(layers, [Fr(0)], [Fr(1)], [Fr(1)], t)
        sol = reluplex(q, tau=1)
        assert (sol is not None) == sat
        if sat:
            assert sol[inputs[0]] == 1


def check_solution(layers, lower, upper, row, t, sol):
    assert all(a <= v <= b for a, v, b in zip(lower, sol, upper))
    z = forward(layers, sol)
    assert sum((r * v for r, v in zip(row, z)), Fr(0)) >= t


def test_against_exhaustive_enumeration():
    rng = random.Random(2017)
    sat_count = 0
    for case in range(500):
        if case % 4 == 3:
            sizes = [2, 2, 1, 2]
        else:
            sizes = [2, rng.randint(1, 3), 2]
        layers = rational_net(rng, sizes)
        lo0 = [Fr(rng.randint(0, 6), 8) for _ in range(2)]
        lower = lo0
        upper = [a + Fr(rng.randint(0, 3), 8) for a in lo0]
        row = [Fr(1), Fr(-1)]
        best = exact_max(layers, lower, upper, row)
        t = best + rng.choice([Fr(-1, 4), Fr(-1, 16), Fr(0), Fr(0), Fr(1, 16), Fr(1, 4)])
        sol = exists_output_at_least(layers, lower, upper, row, t, tau=rng.choice([1, 2, 5]))
        assert (sol is not None) == (best >= t)
        if sol is not None:
            sat_count += 1
            check_solution(layers, lower, upper, row, t, sol)
    assert 150 < sat_count < 450


def test_assignment_meets_the_pairs():
    rng = random.Random(3)
    for _ in range(100):
        layers = rational_net(rng, [2, 3, 2])
        lower, upper = [Fr(0), Fr(0)], [Fr(1), Fr(1)]
        best = exact_max(layers, lower, upper, [Fr(1), Fr(0)])
        q, inputs = encode(layers, lower, upper, [Fr(1), Fr(0)], best)
        sol = reluplex(q)
        assert sol is not None
        for b, f in q.pairs:
            assert sol[f] == max(Fr(0), sol[b])
        for i, r in q.basic.items():
            assert sol[i] == sum((c * sol[j] for j, c in r.items()), Fr(0))


def test_verify_robust_agrees_with_enumeration():
    rng = random.Random(19)
    for _ in range(60):
        layers = rational_net(rng, [2, 3, 2])
        x = [Fr(rng.randint(2, 6), 8), Fr(rng.randint(2, 6), 8)]
        z = forward(layers, x)
        if z[0] == z[1]:
            continue
        y = 0 if z[0] > z[1] else 1
        eps = Fr(rng.randint(0, 2), 8)
        lower = [max(a - eps, Fr(0)) for a in x]
        upper = [min(a + eps, Fr(1)) for a in x]
        row = [Fr(-1), Fr(1)] if y == 0 else [Fr(1), Fr(-1)]
        robust = exact_max(layers, lower, upper, row) < 0
        assert (verify_robust(layers, x, y, eps) is None) == robust

History

Verification of neural networks with SMT solvers was tried before 2017, with general solvers that split every ReLU in advance, and it scaled to very small networks only. Katz, Barrett, Dill, Julian and Kochenderfer presented Reluplex at CAV 2017. They extended the simplex procedure of Dutertre and de Moura (2006), which SMT solvers use for linear real arithmetic, with rules for ReLU pairs, and they verified properties of the deep networks that were proposed for the ACAS Xu airborne collision avoidance system, which were out of reach for earlier tools. The same paper proved that the verification problem for ReLU networks is NP-complete. The group later released Marabou (2019), and the idea of lazy case splits with linear bounds lives on in the branch-and-bound verifiers of today.

References

  1. Guy Katz, Clark Barrett, David L. Dill, Kyle Julian and Mykel J. Kochenderfer, Reluplex, an efficient SMT solver for verifying deep neural networks, CAV 2017, LNCS 10426, pages 97 to 117 (the arXiv version is the extended version), the derivation rules of Reluplex (the simplex rules, the ReLU repair rules and the case split), the proof that the procedure is sound and complete, the NP-completeness proof, and the ACAS Xu case study
  2. Bruno Dutertre and Leonardo de Moura, A fast linear-arithmetic solver for DPLL(T), CAV 2006, LNCS 4144, the general simplex with bounds that Reluplex extends, and its termination with Bland's rule
  3. Nicholas Carlini, Anish Athalye, Nicolas Papernot, Wieland Brendel, Jonas Rauber, Dimitris Tsipras, Ian Goodfellow, Aleksander Madry and Alexey Kurakin, On evaluating adversarial robustness, arXiv 2019, verified robustness as a lower bound on robust accuracy
  4. Battista Biggio and Fabio Roli, Wild patterns: Ten years after the rise of adversarial machine learning, Pattern Recognition 84, pages 317 to 331, 2018, the threat model in three parts used on this page

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example