Algorithm Search⌘K

Algorithmresearch

Linear bound propagation

Also called CROWN.

Bounds each neuron by linear functions of the input through linear relaxations of the activations, which usually gives tighter certificates than intervals.

Time
O(K n N + K n d) worst
Space
O(n^2 + n d + K n) extra
Where
K = the number of layers; N = the number of weights; d = the input dimension; n = the width of the widest layer
Properties
deterministicnot exactofflineiterative
Origin
Eric Wong, J. Zico Kolter, Tsui Wei Weng, Huan Zhang, Gagandeep Singh, Martin Vechev, 2018

Linear bound propagation bounds each output of a ReLU network over an input box by a linear function of the input, and then minimizes that linear function over the box in closed form. Each ReLU whose pre-activation zz can have both signs on the box, with bounds l<0<ul < 0 < u, is replaced by two lines: the chord u(z−l)/(u−l)u(z - l)/(u - l) above it and a line αz\alpha z with 0≤α≤10 \le \alpha \le 1 below it. A backward pass from the output to the input substitutes these lines layer by layer, using the lower line where the coefficient is positive and the upper line where it is negative. CROWN of Zhang et al. (2018) is the best known member of the family; Fast-Lin, the dual network of Wong and Kolter and DeepPoly compute closely related bounds. The bounds are sound and incomplete, and they are usually much tighter than interval bound propagation.

Threat model. The method is a defense, a verifier, so the threat model is the one that the certificate covers. The goal can be untargeted or targeted, since the certificate bounds the margin against every other label. The knowledge is unlimited: the certificate holds against a white-box attacker. The capability is a change at test time within B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d.

In plain words

A ReLU unit is a bent line: flat at zero on the left, rising on the right. Over the inputs that a unit can see, the method traps the bent line between two straight lines, one above and one below.

Once every bent unit is replaced by straight lines, the whole network is trapped between straight functions of the input. The method builds the lower straight function by working back from the output: each time it meets a unit, it picks the line that keeps the result a true lower bound.

A straight function over a box is smallest at a corner, and that corner is easy to find. If the smallest value of the right class minus each other class is positive, the label cannot change. Straight lines keep track of how the units depend on the same inputs, which plain ranges forget.

The problem

Take a network with layers (W1,b1),…,(WK,bK)(W_1, b_1), \dots, (W_K, b_K), a ReLU after every layer except the last, and the pre-activations zk=Wkak−1+bkz_k = W_k a_{k-1} + b_k, a0=xa_0 = x, ak=relu(zk)a_k = \mathrm{relu}(z_k). Given a box l≤x≤ul \le x \le u and a matrix Λ\Lambda, compute a vector m‾\underline m with m‾≤ΛzK(x)\underline m \le \Lambda z_K(x) for every xx in the box. For robustness at xx with label yy, the rows of Λ\Lambda are ey−eje_y - e_j for j≠yj \ne y, the box is B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d, and the point is certified when every entry of m‾\underline m is positive. This is a relaxation of the neural network verification problem, which is NP-complete.

The algorithm

  1. LBP-BACKWARD(layers, k, Λ, l, u) ▷ a lower bound of Λ z_k(x) for l <= x <= u
  2. 1A ← Λ, c ← 0 ▷ the bound so far is A z_j + c
  3. 2for j ← k downto 1 do
  4. 3c ← c + A b_j
  5. 4A ← A W_j ▷ now the bound is A a_{j-1} + c
  6. 5if j > 1 then ▷ a_{j-1} = relu(z_{j-1}), z_{j-1} in [l_{j-1}, u_{j-1}]
  7. 6for each unit i of layer j - 1 do
  8. 7(s+, t+, s-, t-) ← RELAX(l_{j-1,i}, u_{j-1,i})
  9. 8for each row r of A do
  10. 9if A[r, i] >= 0 then c_r ← c_r + A[r, i] t-, A[r, i] ← A[r, i] s-
  11. 10else c_r ← c_r + A[r, i] t+, A[r, i] ← A[r, i] s+
  12. 11m_r ← c_r + sum over t of A[r, t] · (l_t if A[r, t] >= 0 else u_t), for each row r
  13. 12return m
  14. LBP(layers, l, u, Λ)
  15. 13for k ← 1 to K - 1 do
  16. 14l_k ← LBP-BACKWARD(layers, k, I, l, u), u_k ← -LBP-BACKWARD(layers, k, -I, l, u)
  17. 15return LBP-BACKWARD(layers, K, Λ, l, u)

RELAX(l,u)(l, u) returns the slope and intercept of the upper line (s+,t+)(s^+, t^+) and of the lower line (s−,t−)(s^-, t^-) of the ReLU on [l,u][l, u]. If u≤0u \le 0 both lines are 00. If l≥0l \ge 0 both are the identity. Otherwise the upper line is the chord, s+=u/(u−l)s^+ = u/(u - l) and t+=−s+lt^+ = -s^+ l, and the lower line is αz\alpha z with α=1\alpha = 1 if u≥−lu \ge -l and α=0\alpha = 0 if not, the adaptive choice of CROWN. Any α∈[0,1]\alpha \in [0, 1] is sound.

Lines L1 to L4 move the bound through one affine layer, which is exact. Lines L5 to L10 move it through a ReLU layer: a positive coefficient needs a lower bound of the unit (line L9), and a negative coefficient needs an upper bound (line L10). Line L11 minimizes the final linear function of xx over the box, one coordinate at a time. Lines L13 and L14 compute the pre-activation bounds that RELAX needs, layer by layer from the input, with the same backward pass.

Example

Take the network of the interval bound propagation page: W1=(2−11−2)W_1 = \begin{pmatrix} 2 & -1 \\ 1 & -2 \end{pmatrix}, b1=(0,0.5)b_1 = (0, 0.5), W2=(1−1−22)W_2 = \begin{pmatrix} 1 & -1 \\ -2 & 2 \end{pmatrix}, b2=(1,0)b_2 = (1, 0), the point x=(0.5,0.5)x = (0.5, 0.5) with z(x)=(1.5,−1)z(x) = (1.5, -1) and label y=0y = 0, and ϵ=0.25\epsilon = 0.25. The margin is m=z0−z1=3a1−3a2+1m = z_0 - z_1 = 3 a_1 - 3 a_2 + 1, so Λ\Lambda times the last layer has the row (3,−3)(3, -3) and the constant 11.

Lines L13 and L14 give the first-layer bounds z1,1∈[−0.25,1.25]z_{1,1} \in [-0.25, 1.25] and z1,2∈[−0.75,0.75]z_{1,2} \in [-0.75, 0.75], the same as the intervals, since one affine layer is exact. Both units are unstable.

unit [l,u][l, u] upper line lower line (α\alpha) coefficient line used
1 [−0.25,1.25][-0.25, 1.25] 56z+524\tfrac56 z + \tfrac{5}{24} zz (u≥−lu \ge -l, so α=1\alpha = 1) 33 lower (L9)
2 [−0.75,0.75][-0.75, 0.75] 12z+0.375\tfrac12 z + 0.375 zz (u≥−lu \ge -l, so α=1\alpha = 1) −3-3 upper (L10)

The backward pass for Λ\Lambda at k=2k = 2: line L3 gives c=1c = 1 and line L4 gives A=(3,−3)A = (3, -3). Line L9 keeps 3z1,13 z_{1,1}, and line L10 turns −3a2-3 a_2 into −1.5z1,2−1.125-1.5 z_{1,2} - 1.125, so c=−0.125c = -0.125 and A=(3,−1.5)A = (3, -1.5). In the next round line L3 adds Ab1=−0.75A b_1 = -0.75, so c=−0.875c = -0.875, and line L4 gives A=AW1=(4.5,0)A = A W_1 = (4.5, 0). The bound is m≥4.5x1−0.875m \ge 4.5 x_1 - 0.875: the input x2x_2 cancels. Line L11 puts x1=0.25x_1 = 0.25 and gives m‾=0.25>0\underline m = 0.25 > 0, so the point is certified.

Interval bound propagation gives −1.25-1.25 on the same box and fails, and the exact minimum is 11. For ϵ≤1/6\epsilon \le 1/6 the bound is 2.5−9ϵ2.5 - 9\epsilon (it is 1.61.6 at ϵ=0.1\epsilon = 0.1, equal to the exact minimum), and the same formula holds up to ϵ=5/18≈0.278\epsilon = 5/18 \approx 0.278, which is the radius that this method certifies. Interval bounds certify 5/365/36 and the exact radius is 5/125/12.

Correctness

Theorem (soundness). If the bounds lj,ujl_j, u_j used by RELAX contain every pre-activation zj(x)z_j(x) for xx in the box, then the vector mm of line L12 satisfies m≤Λzk(x)m \le \Lambda z_k(x) for every xx in the box. By induction over the layers in line L13, all intermediate bounds are sound, and so is the result of line L15. If every entry is positive for the margin rows, no point of B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d changes the label.

The proof keeps the invariant Λzk(x)≥Av+c\Lambda z_k(x) \ge A v + c for every xx in the box, where vv is zj(x)z_j(x) at the top of round jj and aj−1(x)a_{j-1}(x) after line L4. Lines L3 and L4 are an identity, because zj=Wjaj−1+bjz_j = W_j a_{j-1} + b_j. Line L9 uses Ariai≥Ari(s−zi+t−)A_{ri} a_i \ge A_{ri}(s^- z_i + t^-) for Ari≥0A_{ri} \ge 0, and line L10 uses Ariai≥Ari(s+zi+t+)A_{ri} a_i \ge A_{ri}(s^+ z_i + t^+) for Ari<0A_{ri} < 0; both follow from the two lines of RELAX, which lie below and above the ReLU on [l,u][l, u]. Line L11 is the exact minimum of a linear function over a box. If the first hidden layer is stable on the box, every line is exact, and the bound equals the true minimum. The full proof is in proofs/correctness.md.

Proof: Linear bound propagation gives sound lower bounds, and they are exact when every unit is stablefull

The network has layers (W1,b1),…,(WK,bK)(W_1, b_1), \dots, (W_K, b_K), pre-activations zj=Wjaj−1+bjz_j = W_j a_{j-1} + b_j, activations aj=relu(zj)a_j = \mathrm{relu}(z_j) for j<Kj < K, and a0=xa_0 = x. The box is B={x:l≤x≤u}B = \{x : l \le x \le u\}. Inequalities between vectors hold in each coordinate, and arithmetic is exact.

Lemma 1 (the two lines). Let l≤ul \le u and let RELAX(l,u)=(s+,t+,s−,t−)(l, u) = (s^+, t^+, s^-, t^-). For every z∈[l,u]z \in [l, u],

s−z+t−≤max⁡(z,0)≤s+z+t+.s^- z + t^- \le \max(z, 0) \le s^+ z + t^+.

Proof. If u≤0u \le 0, then max⁡(z,0)=0\max(z, 0) = 0 on [l,u][l, u] and both lines are 00. If l≥0l \ge 0, then max⁡(z,0)=z\max(z, 0) = z and both lines are zz. Otherwise l<0<ul < 0 < u. The upper line g(z)=u(z−l)/(u−l)g(z) = u(z - l)/(u - l) is the chord through (l,0)(l, 0) and (u,u)(u, u). The ReLU is convex, so on [l,u][l, u] it lies below its chord between the two ends. The lower line is αz\alpha z with α∈{0,1}\alpha \in \{0, 1\}. For z≥0z \ge 0, αz≤z=max⁡(z,0)\alpha z \le z = \max(z, 0) since α≤1\alpha \le 1, and for z<0z < 0, αz≤0=max⁡(z,0)\alpha z \le 0 = \max(z, 0) since α≥0\alpha \ge 0. The same argument works for any α∈[0,1]\alpha \in [0, 1]. □\square

Lemma 2 (minimum of a linear function over a box). For a row vector gg and a number cc, min⁡x∈B(gx+c)=c+∑tgt⋅(lt if gt≥0 else ut)\min_{x \in B} (g x + c) = c + \sum_t g_t \cdot (l_t \text{ if } g_t \ge 0 \text{ else } u_t).

Proof. The sum ∑tgtxt\sum_t g_t x_t has one term per coordinate, and the coordinates range independently over [lt,ut][l_t, u_t]. A term with gt≥0g_t \ge 0 is smallest at xt=ltx_t = l_t, and a term with gt<0g_t < 0 is smallest at xt=utx_t = u_t. The point that makes every term smallest is in BB, so it attains the minimum. □\square

Theorem 1 (soundness of one backward pass). Suppose that for every j<kj < k and every x∈Bx \in B, lj≤zj(x)≤ujl_j \le z_j(x) \le u_j. Then LBP-BACKWARD(k,Λ)(k, \Lambda) returns mm with m≤Λzk(x)m \le \Lambda z_k(x) for every x∈Bx \in B.

Proof. Fix x∈Bx \in B and one row rr. We show the invariant: at the top of round jj of line L2, Λrzk(x)≥Arzj(x)+cr\Lambda_r z_k(x) \ge A_r z_j(x) + c_r, and after line L10 of round jj, Λrzk(x)≥Araj−1(x)+cr\Lambda_r z_k(x) \ge A_r a_{j-1}(x) + c_r.

At the start (j=kj = k), line L1 gives A=ΛA = \Lambda and c=0c = 0, so the invariant is an equality. Lines L3 and L4 replace AA by AWjA W_j and cc by c+Abjc + A b_j. Since zj=Wjaj−1+bjz_j = W_j a_{j-1} + b_j, the value Azj+cA z_j + c equals (AWj)aj−1+(c+Abj)(A W_j) a_{j-1} + (c + A b_j), so the inequality carries over to the form in aj−1a_{j-1}. If j=1j = 1, this is the form in a0=xa_0 = x, and the loop ends.

If j>1j > 1, then aj−1=relu(zj−1)a_{j-1} = \mathrm{relu}(z_{j-1}) and by hypothesis zj−1(x)∈[lj−1,uj−1]z_{j-1}(x) \in [l_{j-1}, u_{j-1}]. Lines L6 to L10 treat one unit ii at a time, and each step changes only column ii of AA and the constant cc. Let (s+,t+,s−,t−)(s^+, t^+, s^-, t^-) be the lines of unit ii. If Ari≥0A_{ri} \ge 0, Lemma 1 gives Ari aj−1,i≥Ari(s−zj−1,i+t−)A_{ri}\, a_{j-1,i} \ge A_{ri}(s^- z_{j-1,i} + t^-), which is line L9. If Ari<0A_{ri} < 0, multiplying the upper line by a negative number gives Ari aj−1,i≥Ari(s+zj−1,i+t+)A_{ri}\, a_{j-1,i} \ge A_{ri}(s^+ z_{j-1,i} + t^+), which is line L10. In both cases the right side is no larger, so the inequality still holds after the step. After all units, column ii multiplies zj−1,iz_{j-1,i} for every ii, which is the invariant at the top of round j−1j - 1.

When the loop ends, Λrzk(x)≥Arx+cr\Lambda_r z_k(x) \ge A_r x + c_r for every x∈Bx \in B. Line L11 computes min⁡x∈B(Arx+cr)\min_{x \in B}(A_r x + c_r) by Lemma 2, which is at most Arx+crA_r x + c_r for each xx. So mr≤Λrzk(x)m_r \le \Lambda_r z_k(x). □\square

Theorem 2 (soundness of LBP and of the certificate). LBP(l,u,Λ)(l, u, \Lambda) returns mm with m≤ΛzK(x)m \le \Lambda z_K(x) for every x∈Bx \in B. If Λ\Lambda has the rows ey−eje_y - e_j for j≠yj \ne y, the box is B∞(x0,ϵ)∩[0,1]dB_\infty(x_0, \epsilon) \cap [0,1]^d, and every entry of mm is positive, then yy is the only argmax of zK(x)z_K(x) for every xx in the box.

Proof. By induction on kk in line L13. Assume that the bounds of the layers 1,…,k−11, \dots, k - 1 are sound (for k=1k = 1 there is nothing to assume). Theorem 1 with Λ=I\Lambda = I gives lk≤zk(x)l_k \le z_k(x), and with Λ=−I\Lambda = -I it gives −zk(x)≥-z_k(x) \ge LBP-BACKWARD(k,−I)(k, -I), that is zk(x)≤ukz_k(x) \le u_k. So the bounds of layer kk are sound. After the loop, the hypothesis of Theorem 1 holds for k=Kk = K, and line L15 gives the claim. For the certificate, (ey−ej)zK(x)=zy(x)−zj(x)≥mj>0(e_y - e_j) z_K(x) = z_y(x) - z_j(x) \ge m_j > 0 for every j≠yj \ne y. □\square

Theorem 3 (exact on stable networks). If K=2K = 2 and every unit of the hidden layer has u1,i≤0u_{1,i} \le 0 or l1,i≥0l_{1,i} \ge 0, then mr=min⁡x∈BΛrz2(x)m_r = \min_{x \in B} \Lambda_r z_2(x).

Proof. For K=2K = 2, the bounds of line L14 for k=1k = 1 come from one affine layer with no ReLU, so they are the exact minimum and maximum of each z1,iz_{1,i} over BB by Lemma 2. If u1,i≤0u_{1,i} \le 0, then a1,i=0a_{1,i} = 0 on BB and both lines are 00; if l1,i≥0l_{1,i} \ge 0, then a1,i=z1,ia_{1,i} = z_{1,i} and both lines are the identity. So every step of lines L9 and L10 is an equality for every x∈Bx \in B, and the loop ends with Λrz2(x)=Arx+cr\Lambda_r z_2(x) = A_r x + c_r on BB. Line L11 is the exact minimum by Lemma 2. ■\blacksquare

Complexity

  • Time. One backward pass from layer kk with rr rows costs O(rN)O(r N) for lines L3 and L4 over all layers, plus O(rn)O(r n) per ReLU layer. Line L14 runs it with r=2nkr = 2 n_k rows for every hidden layer, so the total is O(KnN)O(K n N), plus O(Knd)O(K n d) for line L11. This is about nn times more than interval bounds.
  • Space. The matrix AA has rr rows and at most max⁡(n,d)\max(n, d) columns, so O(n2+nd)O(n^2 + n d), plus O(Kn)O(K n) for the stored bounds.
  • Cheaper forms. Bounding only the last layer with linear bounds and the hidden layers with intervals (CROWN-IBP) costs O(kN)O(k N) for kk logits.

Properties

  • Sound, not complete. A positive bound is a proof (a theorem); a negative one proves nothing.
  • A lower bound on robust accuracy. The certified fraction of a test set is a lower bound, and an attack gives an upper bound.
  • Exact on stable networks. If no unit is unstable on the box, every substitution is exact and the bound equals the true minimum.
  • Usually tighter than intervals, but not always. With the adaptive α\alpha, the bound is not always above the interval bound. On 2000 random networks with 2 inputs and 2 to 6 hidden units at ϵ=0.2\epsilon = 0.2, it was tighter in 1102 cases, equal in 696 and looser in 202 (a measurement made for this page). Taking the larger of the two bounds is always sound.
  • Linear in the margin. The bound of a sum of rows is at least the sum of the bounds, so folding the margin into Λ\Lambda (as in the example) is better than bounding each logit alone.

Variants and improvements

  • Fast-Lin. Weng et al. (2018) use the chord slope for the lower line too, s−=s+s^- = s^+ and t−=0t^- = 0, which makes the two lines parallel.
  • Optimized slopes. The lower slope α\alpha of each unit can be any number in [0,1][0, 1]. Choosing it by gradient steps on the final bound (alpha-CROWN, Xu et al. 2021) gives tighter bounds at a higher cost.
  • The dual view. Wong and Kolter (2018) bound the same relaxation through the Lagrangian dual of a linear program, and they train networks against the bound.
  • DeepPoly. Singh et al. (2019) keep one lower and one upper linear bound per neuron, in terms of the previous layer, and back-substitute to the input, as an abstract domain in the sense of abstract interpretation.
  • Branch and bound. Splitting an unstable unit into its two phases removes its relaxation. Doing this in a search tree, with linear bounds at each node, gives complete verifiers such as beta-CROWN (Wang et al. 2021), which are compared with Reluplex on the same problems.

When to use it

Use linear bound propagation to verify a network that was trained without a verifier in mind, when interval bounds are too loose and an exact method such as Reluplex is too slow. It is also the bounding step inside most modern complete verifiers. For very large models or large ℓ2\ell_2 radii, randomized smoothing is the usual alternative.

Pitfalls

  • The wrong line for the sign. Line L9 must use the lower line for a positive coefficient and line L10 the upper line for a negative one. Swapping them gives a number that is not a bound at all, and it can certify a point that has an adversarial example.
  • Intermediate bounds from the wrong layer. RELAX at line L7 needs the bounds of the pre-activation zj−1z_{j-1}, computed by line L14 before the backward pass reaches it. Using the bounds after the ReLU, or the bounds of another layer, breaks the invariant.
  • An unsound lower slope. A lower line αz\alpha z with α\alpha outside [0,1][0, 1], or the chord used as a lower line with a nonzero intercept, crosses above the ReLU on part of [l,u][l, u].
  • Expecting it to beat intervals every time. As the properties above show, the adaptive α\alpha can lose to interval bounds. A verifier that wants the best of both takes the elementwise maximum of the two lower bounds.
  • Floating point. The theorem is in exact arithmetic. A certificate meant as a proof must round outward in lines L3, L4 and L11.

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, either with random weights or from mlkit.tiny_relu_net, on seeded random inputs. It never reads real data or touches a real system. The tests check the example and the radius 5/185/18, that the two lines of RELAX bound the ReLU, that the first-layer bounds equal the exact intervals, that a point box is exact, soundness on 500 random networks against the exact range from an enumeration of all activation patterns and against sampling, exactness when the first layer is stable, and that no sampled input breaks a certified point.

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.

linear_bound_propagation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-bound-propagation/. The authors are listed in prov/2XBS61.jsonl.

"""Linear bound propagation in the style of CROWN for feed-forward ReLU networks.

A network is a list of affine layers (W, b), with a ReLU after every layer except the
last. Each unstable ReLU, with pre-activation bounds l < 0 < u, is bounded above by the
chord u (z - l) / (u - l) and below by alpha z, with alpha = 1 if u >= -l and 0 if not
(the adaptive choice of Zhang et al. 2018). A backward pass turns a linear objective
of one layer into a linear function of the input, which is then minimized over the
input box in closed form. The bounds hold in exact arithmetic; floats add rounding.

The models in the tests are synthetic networks built from a fixed seed.
"""

from typing import Sequence

Vector = list[float]
Matrix = list[list[float]]
Layer = tuple[list[list[float]], list[float]]


def layers_from_net(net: dict) -> list[Layer]:
    """The two layers of a tiny_relu_net dict of mlkit. Cost O(h d + k h)."""
    return [([list(r) for r in net["W1"]], list(net["b1"])), ([list(r) for r in net["W2"]], list(net["b2"]))]


def forward(layers: Sequence[Layer], x: Sequence[float]) -> Vector:
    """The outputs of the last layer at x. Cost O(sum of the layer sizes)."""
    a = list(x)
    for k, (w, b) in enumerate(layers):
        a = [sum(wi * ai for wi, ai in zip(row, a, strict=True)) + bi for row, bi in zip(w, b, strict=True)]
        if k < len(layers) - 1:
            a = [max(v, 0.0) for v in a]
    return a


def relaxation(l: float, u: float) -> tuple[float, float, float, float]:
    """(upper slope, upper intercept, lower slope, lower intercept) of relu on [l, u].

    Precondition l <= u. Every z in [l, u] has
    lower slope * z + lower intercept <= relu(z) <= upper slope * z + upper intercept.
    """
    if u <= 0.0:
        return 0.0, 0.0, 0.0, 0.0
    if l >= 0.0:
        return 1.0, 0.0, 1.0, 0.0
    s = u / (u - l)
    alpha = 1.0 if u >= -l else 0.0
    return s, -s * l, alpha, 0.0


def backward_bound(layers: Sequence[Layer], k: int, lam: Matrix, bounds: Sequence[tuple[Vector, Vector]],
                   lower: Sequence[float], upper: Sequence[float]) -> Vector:
    """Lower bounds of the rows of lam times z_k over the box, where z_k is the output of layer k (0-based).

    bounds[j] holds (l, u) for the pre-activations of layer j, for every j < k.
    Precondition: lower <= upper, and the sizes match. Cost O(r N) for r rows and N
    weights in the layers 0 .. k.
    """
    a = [list(row) for row in lam]  # @line L1
    c = [0.0] * len(a)  # @line L1
    for j in range(k, -1, -1):  # @line L2
        w, b = layers[j]
        for r, row in enumerate(a):  # @line L3
            c[r] += sum(ai * bi for ai, bi in zip(row, b, strict=True))  # @line L3
        a = [[sum(row[i] * w[i][t] for i in range(len(w))) for t in range(len(w[0]))] for row in a]  # @line L4
        if j > 0:  # @line L5
            lj, uj = bounds[j - 1]
            for i in range(len(lj)):  # @line L6
                su, iu, sl, il = relaxation(lj[i], uj[i])  # @line L7
                for r, row in enumerate(a):  # @line L8
                    if row[i] >= 0.0:  # @line L9
                        c[r] += row[i] * il  # @line L9
                        row[i] *= sl  # @line L9
                    else:  # @line L10
                        c[r] += row[i] * iu  # @line L10
                        row[i] *= su  # @line L10
    out = []
    for r, row in enumerate(a):  # @line L11
        out.append(c[r] + sum(ai * (lo if ai >= 0.0 else hi) for ai, lo, hi in zip(row, lower, upper, strict=True)))  # @line L11
    return out  # @line L12


def linear_bound_propagation(layers: Sequence[Layer], lower: Sequence[float], upper: Sequence[float],
                             spec: Matrix) -> Vector:
    """Lower bounds of spec times the network output, over the box [lower, upper].

    The pre-activation bounds of each hidden layer are computed first, by the same
    backward pass with the identity and its negation as objectives.
    Precondition: lower <= upper; spec has as many columns as the last layer has rows.
    Cost O(K n N) for K layers, n units per layer at most and N weights in total.
    """
    bounds: list[tuple[Vector, Vector]] = []
    for k in range(len(layers) - 1):  # @line L13
        n = len(layers[k][0])
        eye = [[1.0 if i == t else 0.0 for t in range(n)] for i in range(n)]
        neg = [[-v for v in row] for row in eye]
        lo = backward_bound(layers, k, eye, bounds, lower, upper)  # @line L14
        hi = [-v for v in backward_bound(layers, k, neg, bounds, lower, upper)]  # @line L14
        bounds.append((lo, hi))  # @line L14
    return backward_bound(layers, len(layers) - 1, spec, bounds, lower, upper)  # @line L15


def margin_spec(k: int, y: int) -> Matrix:
    """The rows e_y - e_j for j != y, so that spec times z is the vector of margins. Cost O(k^2)."""
    return [[(1.0 if t == y else 0.0) - (1.0 if t == j else 0.0) for t in range(k)] for j in range(k) if j != y]


def certify_crown(layers: Sequence[Layer], x: Sequence[float], y: int, epsilon: float) -> tuple[bool, Vector]:
    """Try to certify that y is the only argmax on B_infinity(x, epsilon) in [0, 1]^d.

    Returns (certified, l) with l the lower bounds of z_y - z_j for j != y. True is a
    proof in exact arithmetic; False proves nothing. Cost as linear_bound_propagation.
    """
    lower = [max(a - epsilon, 0.0) for a in x]
    upper = [min(a + epsilon, 1.0) for a in x]
    lo = linear_bound_propagation(layers, lower, upper, margin_spec(len(layers[-1][0]), y))
    return all(v > 0.0 for v in lo), lo
mlkit.py 252 lines
# 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)
test_linear_bound_propagation.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/linear-bound-propagation/. The authors are listed in prov/2XBS61.jsonl.

"""Tests of linear bound propagation (CROWN) on seeded synthetic ReLU networks only."""

import itertools
import random

import mlkit as m
from linear_bound_propagation import (
    backward_bound,
    certify_crown,
    forward,
    layers_from_net,
    linear_bound_propagation,
    margin_spec,
    relaxation,
)

TOL = 1e-9

# The network of the worked example: two inputs, two hidden ReLUs, two logits.
EXAMPLE = [([[2.0, -1.0], [1.0, -2.0]], [0.0, 0.5]), ([[1.0, -1.0], [-2.0, 2.0]], [1.0, 0.0])]


def box(x, epsilon):
    return [max(a - epsilon, 0.0) for a in x], [min(a + epsilon, 1.0) for a in x]


def exact_range(layers, lower, upper, row):
    """Exact (min, max) of row times the output of layers over a 2-dimensional box.

    The oracle enumerates every activation pattern of the hidden units. On the region
    of one pattern the network is affine, so its extremes over the region are at
    vertices; each vertex is the meet of two constraint lines, solved by Cramer's rule.
    """
    d = len(lower)
    assert d == 2
    sizes = [len(w) for w, _ in layers[:-1]]
    best_lo, best_hi = None, None
    for pat in itertools.product([0, 1], repeat=sum(sizes)):
        cons = [([1.0, 0.0], -lower[0]), ([-1.0, 0.0], upper[0]), ([0.0, 1.0], -lower[1]), ([0.0, -1.0], upper[1])]
        a = [[1.0, 0.0], [0.0, 1.0]]
        c = [0.0, 0.0]
        p = 0
        for k, (w, b) in enumerate(layers):
            a2 = [[sum(w[i][t] * a[t][j] for t in range(len(a))) for j in range(d)] for i in range(len(w))]
            c2 = [sum(w[i][t] * c[t] for t in range(len(c))) + 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] = [0.0] * d, 0.0
                    p += 1
            a, c = a2, c2
        g = [sum(row[i] * a[i][j] for i in range(len(row))) for j in range(d)]
        g0 = sum(row[i] * c[i] for i in range(len(row)))
        for (r1, c1), (r2, c2v) in itertools.combinations(cons, 2):
            det = r1[0] * r2[1] - r1[1] * r2[0]
            if abs(det) < 1e-12:
                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 >= -1e-9 for r, cc in cons):
                v = g[0] * x0 + g[1] * x1 + g0
                best_lo = v if best_lo is None else min(best_lo, v)
                best_hi = v if best_hi is None else max(best_hi, v)
    return best_lo, best_hi


def random_layers(rng: random.Random, sizes: list[int]) -> list:
    out = []
    for n_in, n_out in zip(sizes, sizes[1:]):
        out.append(([[rng.uniform(-2, 2) for _ in range(n_in)] for _ in range(n_out)], [rng.uniform(-1, 1) for _ in range(n_out)]))
    return out


def test_example():
    ok, lo = certify_crown(EXAMPLE, [0.5, 0.5], 0, 0.25)
    assert ok and abs(lo[0] - 0.25) < TOL
    ok, lo = certify_crown(EXAMPLE, [0.5, 0.5], 0, 0.1)
    assert ok and abs(lo[0] - 1.6) < TOL
    lower, upper = box([0.5, 0.5], 0.25)
    assert exact_range(EXAMPLE, lower, upper, [1.0, -1.0])[0] == 1.0
    assert relaxation(-0.25, 1.25) == (1.25 / 1.5, 1.25 / 1.5 * 0.25, 1.0, 0.0)
    assert relaxation(-0.75, 0.75) == (0.5, 0.375, 1.0, 0.0)


def test_example_radius_is_5_over_18():
    lo, hi = 0.0, 0.5
    for _ in range(60):
        mid = (lo + hi) / 2
        if certify_crown(EXAMPLE, [0.5, 0.5], 0, mid)[0]:
            lo = mid
        else:
            hi = mid
    assert abs(lo - 5 / 18) < 1e-9


def test_relaxation_is_sound():
    rng = random.Random(1)
    for _ in range(500):
        l = rng.uniform(-2, 2)
        u = l + rng.uniform(0, 3)
        su, iu, sl, il = relaxation(l, u)
        for t in range(21):
            z = l + (u - l) * t / 20
            assert sl * z + il <= max(z, 0.0) + 1e-12 <= su * z + iu + 2e-12


def test_first_layer_bounds_are_the_exact_intervals():
    rng = random.Random(2)
    for _ in range(200):
        d = rng.randint(1, 4)
        layers = random_layers(rng, [d, 3])
        lower = [rng.uniform(0, 0.5) for _ in range(d)]
        upper = [a + rng.uniform(0, 0.5) for a in lower]
        eye = [[1.0 if i == t else 0.0 for t in range(3)] for i in range(3)]
        lo = backward_bound(layers, 0, eye, [], lower, upper)
        corners = [forward(layers, list(c)) for c in itertools.product(*zip(lower, upper))]
        for i in range(3):
            assert abs(lo[i] - min(v[i] for v in corners)) < 1e-9


def test_point_box_is_exact():
    rng = random.Random(3)
    for _ in range(100):
        layers = random_layers(rng, [3, 4, 3, 2])
        x = [rng.random() for _ in range(3)]
        lo = linear_bound_propagation(layers, x, x, [[1.0, -1.0], [-1.0, 1.0]])
        z = forward(layers, x)
        assert abs(lo[0] - (z[0] - z[1])) < 1e-9 and abs(lo[1] - (z[1] - z[0])) < 1e-9


def test_mlkit_network_conversion():
    rng = random.Random(4)
    net = m.tiny_relu_net(rng, 4, 6, 3)
    layers = layers_from_net(net)
    for _ in range(20):
        x = [rng.random() for _ in range(4)]
        assert all(abs(a - b) < 1e-12 for a, b in zip(forward(layers, x), m.forward(net, x)))


def test_sound_against_enumeration_and_sampling():
    rng = random.Random(2018)
    stable_exact = 0
    for case in range(500):
        if case % 3 == 2:
            sizes = [2, 2, 2, 2]
        else:
            sizes = [2, rng.randint(1, 4), rng.randint(2, 3)]
        layers = random_layers(rng, sizes)
        x = [rng.random(), rng.random()]
        epsilon = rng.choice([0.0, 0.05, 0.1, 0.2, 0.4])
        y = rng.randrange(sizes[-1])
        lower, upper = box(x, epsilon)
        spec = margin_spec(sizes[-1], y)
        lo = linear_bound_propagation(layers, lower, upper, spec)
        j = rng.randrange(len(spec))
        ex_lo, ex_hi = exact_range(layers, lower, upper, spec[j])
        assert lo[j] <= ex_lo + 1e-9
        hi = -linear_bound_propagation(layers, lower, upper, [[-v for v in spec[j]]])[0]
        assert ex_hi <= hi + 1e-9
        for _ in range(30):
            p = [rng.uniform(a, b) for a, b in zip(lower, upper)]
            z = forward(layers, p)
            margins = [sum(s * v for s, v in zip(row, z)) for row in spec]
            assert all(a - 1e-9 <= b for a, b in zip(lo, margins))
        if len(sizes) == 3:
            eye = [[1.0 if i == t else 0.0 for t in range(sizes[1])] for i in range(sizes[1])]
            l1 = backward_bound(layers, 0, eye, [], lower, upper)
            u1 = [-v for v in backward_bound(layers, 0, [[-v for v in r] for r in eye], [], lower, upper)]
            if all(a >= 0.0 or b <= 0.0 for a, b in zip(l1, u1)):
                stable_exact += 1
                assert abs(lo[j] - ex_lo) < 1e-7
        ok, _ = certify_crown(layers, x, y, epsilon)
        if ok:
            assert min(exact_range(layers, lower, upper, row)[0] for row in spec) > 0.0
    assert stable_exact > 50


def test_certified_points_have_no_sampled_counterexample():
    rng = random.Random(11)
    net = m.tiny_relu_net(rng, 3, 5, 3)
    layers = layers_from_net(net)
    count = 0
    for _ in range(200):
        x = [rng.random() for _ in range(3)]
        y = m.argmax(m.forward(net, x))
        ok, _ = certify_crown(layers, x, y, 0.05)
        if ok:
            count += 1
            lower, upper = box(x, 0.05)
            for _ in range(20):
                p = [rng.uniform(a, b) for a, b in zip(lower, upper)]
                assert m.argmax(m.forward(net, p)) == y
    assert count > 0

History

After adversarial examples were found, exact verifiers such as Reluplex (2017) showed that verification is possible but slow. In 2018 several groups found fast sound bounds from linear relaxations of the ReLU. Wong and Kolter (ICML 2018) used the convex outer bound of the ReLU and its dual network, and trained networks to be provably robust. Weng et al. (ICML 2018) gave Fast-Lin with parallel linear bounds, and Zhang et al. (NeurIPS 2018) gave CROWN, with separate upper and lower lines and support for general activations. Singh et al. described the same kind of bound as the DeepPoly abstract domain (POPL 2019). Later work optimized the slopes and combined the bounds with branch and bound, and verifiers built this way are now the usual tools for complete verification of ReLU networks.

References

  1. Huan Zhang, Tsui-Wei Weng, Pin-Yu Chen, Cho-Jui Hsieh and Luca Daniel, Efficient neural network robustness certification with general activation functions, NeurIPS 2018, the linear upper and lower bounds of each activation, the adaptive lower bound for ReLU, and the backward computation of the bound of each layer
  2. Tsui-Wei Weng, Huan Zhang, Hongge Chen, Zhao Song, Cho-Jui Hsieh, Luca Daniel, Duane Boning and Inderjit Dhillon, Towards fast computation of certified robustness for ReLU networks, ICML 2018, PMLR 80, pages 5276 to 5285, Fast-Lin, the linear bounds of ReLU networks with equal upper and lower slopes, and the hardness of the exact minimum distortion
  3. Eric Wong and J. Zico Kolter, Provable defenses against adversarial examples via the convex outer adversarial polytope, ICML 2018, PMLR 80, pages 5286 to 5295, the convex relaxation of the ReLU, its dual network, and training against the bound
  4. Gagandeep Singh, Timon Gehr, Markus Püschel and Martin Vechev, An abstract domain for certifying neural networks, Proceedings of the ACM on Programming Languages 3, POPL 2019, the DeepPoly domain, with one linear lower and one linear upper bound per neuron and back-substitution
  5. 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