Algorithm Search⌘K

Algorithmadvanced

Interval bound propagation

Also called IBP.

Pushes an input box through the network layer by layer with interval arithmetic, to certify robustness and to train certifiably robust models.

Time
Θ(N + d) worst
Space
Θ(n + d) extra
Where
N = the number of weights of the network; d = the input dimension; n = the width of the widest layer
Properties
deterministicnot exactofflineiterative
Origin
Matthew Mirman, Timon Gehr, Martin Vechev, Sven Gowal, Krishnamurthy Dvijotham, Robert Stanforth, 2018

Interval bound propagation (IBP) computes, for every output of a ReLU network, a lower and an upper bound that hold for every input in a box. It pushes the box through the network one layer at a time. An affine layer maps a box with center μ\mu and radius rr into the box with center Wμ+bW\mu + b and radius ∣W∣r|W| r, and a ReLU maps an interval [l,u][l, u] to [max⁡(l,0),max⁡(u,0)][\max(l, 0), \max(u, 0)]. To certify that a classifier keeps the label yy on B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d, IBP bounds the margins zy−zjz_y - z_j from below; if every lower bound is positive, no input of the box changes the label. The method is sound and incomplete: a positive answer is a proof, a negative answer proves nothing. It costs about two forward passes, so Gowal et al. (2018) could use it inside the training loss of large networks.

Threat model. IBP is a defense, so the threat model is the one that the certificate covers. The goal can be untargeted or targeted, since a certificate for all labels j≠yj \ne y covers both. The knowledge is unlimited: the certificate holds against a white-box attacker who knows the weights. The capability is a change at test time within B∞(x,ϵ)∩[0,1]dB_\infty(x, \epsilon) \cap [0,1]^d.

In plain words

Suppose each input number may move a little, inside a known range. IBP asks how far each number in the next layer can move as a result, and it answers with a range again: the smallest and the largest value that the number can take.

For a weighted sum the answer is simple. The middle of the range is the weighted sum of the middles, and the width grows by the size of each weight, whatever its sign. For a ReLU, which sets negative numbers to zero, the range is cut at zero.

At the end the method has a range for each output score. If the lowest possible score of the right class is above the highest possible score of every other class, no allowed change can make the model wrong. If not, the method cannot tell, because its ranges are often too wide.

The problem

Take a network with logits z(x)=WK relu(⋯relu(W1x+b1)⋯ )+bKz(x) = W_K\, \mathrm{relu}(\cdots \mathrm{relu}(W_1 x + b_1) \cdots) + b_K in Rk\mathbb{R}^k, an input x∈[0,1]dx \in [0,1]^d with label yy and a radius ϵ≥0\epsilon \ge 0. Let S=B∞(x,ϵ)∩[0,1]dS = B_\infty(x, \epsilon) \cap [0,1]^d. The verification question of the neural network verification problem is whether zy(x′)−zj(x′)>0z_y(x') - z_j(x') > 0 for every x′∈Sx' \in S and every j≠yj \ne y. IBP answers a weaker question: it computes numbers m‾j\underline m_j with m‾j≤min⁡x′∈S(zy(x′)−zj(x′))\underline m_j \le \min_{x' \in S} (z_y(x') - z_j(x')), and it reports "certified" when every m‾j>0\underline m_j > 0.

The algorithm

  1. IBP(layers (W_1, b_1) .. (W_K, b_K), l, u) ▷ the box l <= x <= u
  2. 1l, u ← the input box
  3. 2for k ← 1 to K do
  4. 3mu ← (u + l)/2, r ← (u - l)/2 ▷ center and radius
  5. 4mu ← W_k mu + b_k
  6. 5r ← |W_k| r ▷ |W_k| takes the absolute value of each entry
  7. 6l ← mu - r, u ← mu + r
  8. 7if k < K then ▷ a ReLU follows every layer but the last
  9. 8l ← max(l, 0), u ← max(u, 0)
  10. 9return (l, u)
  11. CERTIFY-IBP(layers, x, y, epsilon)
  12. 10l ← max(x - epsilon, 0), u ← min(x + epsilon, 1)
  13. 11replace (W_K, b_K) by the rows W_K[y] - W_K[j] and the entries b_K[y] - b_K[j], for j != y
  14. 12(l', u') ← IBP(layers, l, u)
  15. 13return min_j l'_j > 0

Line L1 starts from the input box. Line L3 writes the current box in center and radius form. Lines L4 and L5 apply the affine layer: the center moves like a point, and the radius grows by the absolute weights, because the term W(v−μ)W(v - \mu) is largest in coordinate ii when each vt−μtv_t - \mu_t has the sign of WitW_{it}. Line L8 applies the ReLU to both ends, which is exact for one monotone function of one variable.

Line L10 builds the box of the threat model, cut to the valid range. Line L11 folds the margins zy−zjz_y - z_j into the last layer, so that line L12 bounds each margin directly and not the two logits on their own. Line L13 needs a strictly positive lower bound, so a tie counts as not certified.

Example

Take d=2d = 2, two hidden ReLUs and two logits, with 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). At x=(0.5,0.5)x = (0.5, 0.5) the hidden layer is (0.5,0)(0.5, 0) and the logits are z(x)=(1.5,−1)z(x) = (1.5, -1), so y=0y = 0. Line L11 gives the margin m=z0−z1=3h1−3h2+1m = z_0 - z_1 = 3 h_1 - 3 h_2 + 1, where h=relu(W1x+b1)h = \mathrm{relu}(W_1 x + b_1). Take ϵ=0.25\epsilon = 0.25, so the box of line L10 is [0.25,0.75]2[0.25, 0.75]^2.

step center μ\mu radius rr lower ll upper uu
input (L1, L3) (0.5,0.5)(0.5, 0.5) (0.25,0.25)(0.25, 0.25) (0.25,0.25)(0.25, 0.25) (0.75,0.75)(0.75, 0.75)
layer 1 (L4 to L6) (0.5,0)(0.5, 0) (0.75,0.75)(0.75, 0.75) (−0.25,−0.75)(-0.25, -0.75) (1.25,0.75)(1.25, 0.75)
ReLU (L8) (0,0)(0, 0) (1.25,0.75)(1.25, 0.75)
margin layer (L3 to L6) 1.751.75 33 −1.25-1.25 4.754.75

The lower bound −1.25-1.25 is negative, so IBP does not certify the point at ϵ=0.25\epsilon = 0.25. The point is robust all the same: the true minimum of mm over the box is 11, which Reluplex proves exactly and linear bound propagation bounds from below by 0.250.25. The loss comes from line L5 in the margin layer: the radius 3⋅0.625+3⋅0.3753 \cdot 0.625 + 3 \cdot 0.375 treats h1h_1 and h2h_2 as free to move in opposite directions, while both depend on the same two inputs.

At ϵ=0.1\epsilon = 0.1 both hidden bounds are [0.2,0.8][0.2, 0.8] and [−0.3,0.3][-0.3, 0.3], and the margin bound is 2.05−1.35=0.7>02.05 - 1.35 = 0.7 > 0, so IBP certifies. For ϵ≤1/6\epsilon \le 1/6 the first hidden unit stays positive on the box, and the bound is 2.5−18ϵ2.5 - 18\epsilon. It is positive exactly when ϵ<5/36≈0.139\epsilon < 5/36 \approx 0.139, so that is the radius that IBP certifies. The exact robust radius of this point is 5/12≈0.4175/12 \approx 0.417.

Correctness

Theorem (soundness). If l≤ul \le u on input, then for every vv with l≤v≤ul \le v \le u, the output f(v)f(v) of the layers satisfies l′≤f(v)≤u′l' \le f(v) \le u' for the pair (l′,u′)(l', u') of line L9. So if CERTIFY-IBP returns true, then zy(x′)>zj(x′)z_y(x') > z_j(x') for every x′∈B∞(x,ϵ)∩[0,1]dx' \in B_\infty(x, \epsilon) \cap [0,1]^d and every j≠yj \ne y.

The proof is an induction on the layers. If ∣vt−μt∣≤rt|v_t - \mu_t| \le r_t for every tt, then ∣(Wv+b)i−(Wμ+b)i∣=∣∑tWit(vt−μt)∣≤∑t∣Wit∣rt|(Wv + b)_i - (W\mu + b)_i| = |\sum_t W_{it}(v_t - \mu_t)| \le \sum_t |W_{it}| r_t, which is lines L4 to L6. The ReLU is nondecreasing, so l≤a≤ul \le a \le u gives max⁡(l,0)≤max⁡(a,0)≤max⁡(u,0)\max(l, 0) \le \max(a, 0) \le \max(u, 0), which is line L8. After line L11 the outputs of the last layer are exactly the margins, so positive lower bounds rule out every label change. The bound of one affine layer is also tight: each end is reached at a corner of the box. The full proof is in proofs/correctness.md.

The theorem is about exact arithmetic. With floating point numbers, the bounds can be off by rounding; a verifier that must be sound on floats rounds every lower bound down and every upper bound up, as in interval arithmetic.

Proof: Interval bound propagation gives sound bounds, and a certificate rules out every label change in the boxfull

A network is a list of affine layers (W1,b1),…,(WK,bK)(W_1, b_1), \dots, (W_K, b_K), with a ReLU after every layer except the last. We write f(v)f(v) for the output of layer KK at the input vv, and we compare vectors coordinate by coordinate. Arithmetic is exact.

Lemma 1 (an affine layer). Let μ,r\mu, r be vectors with r≥0r \ge 0, and let vv satisfy ∣vt−μt∣≤rt|v_t - \mu_t| \le r_t for every tt. Then for every row ii,

(Wμ+b)i−(∣W∣r)i≤(Wv+b)i≤(Wμ+b)i+(∣W∣r)i.(W\mu + b)_i - (|W| r)_i \le (Wv + b)_i \le (W\mu + b)_i + (|W| r)_i.

Both ends are reached: the upper one at vt=μt+sign⁡(Wit)rtv_t = \mu_t + \operatorname{sign}(W_{it}) r_t, the lower one at vt=μt−sign⁡(Wit)rtv_t = \mu_t - \operatorname{sign}(W_{it}) r_t.

Proof. (Wv+b)i−(Wμ+b)i=∑tWit(vt−μt)(Wv + b)_i - (W\mu + b)_i = \sum_t W_{it}(v_t - \mu_t). By the triangle inequality, ∣∑tWit(vt−μt)∣≤∑t∣Wit∣ ∣vt−μt∣≤∑t∣Wit∣rt|\sum_t W_{it}(v_t - \mu_t)| \le \sum_t |W_{it}|\,|v_t - \mu_t| \le \sum_t |W_{it}| r_t. At the given points every term Wit(vt−μt)W_{it}(v_t - \mu_t) equals ±∣Wit∣rt\pm |W_{it}| r_t with the same sign for all tt, so the bound is an equality. □\square

Lemma 2 (a ReLU). If l≤a≤ul \le a \le u, then max⁡(l,0)≤max⁡(a,0)≤max⁡(u,0)\max(l, 0) \le \max(a, 0) \le \max(u, 0), and both ends are reached on [l,u][l, u].

Proof. The function t↦max⁡(t,0)t \mapsto \max(t, 0) is nondecreasing, which gives the inequalities. It is continuous, so by the intermediate value theorem it takes every value between max⁡(l,0)\max(l, 0) and max⁡(u,0)\max(u, 0) on [l,u][l, u]; in particular it takes the two ends, at t=lt = l and t=ut = u. □\square

Theorem 1 (soundness of IBP). Let l≤ul \le u be the input box of line L1, and let (l(k),u(k))(l^{(k)}, u^{(k)}) be the box after layer kk in the loop of lines L2 to L8. For every input vv with l≤v≤ul \le v \le u, the activation a(k)(v)a^{(k)}(v) of layer kk (after its ReLU when k<Kk < K) satisfies l(k)≤a(k)(v)≤u(k)l^{(k)} \le a^{(k)}(v) \le u^{(k)}. In particular the pair (l′,u′)(l', u') of line L9 bounds f(v)f(v).

Proof. By induction on kk. For k=0k = 0 the claim is the hypothesis l≤v≤ul \le v \le u. Assume the claim for k−1k - 1. Line L3 sets μ=(u(k−1)+l(k−1))/2\mu = (u^{(k-1)} + l^{(k-1)})/2 and r=(u(k−1)−l(k−1))/2≥0r = (u^{(k-1)} - l^{(k-1)})/2 \ge 0, so l(k−1)≤a≤u(k−1)l^{(k-1)} \le a \le u^{(k-1)} is the same as ∣at−μt∣≤rt|a_t - \mu_t| \le r_t for every tt. By Lemma 1, the pre-activation Wka+bkW_k a + b_k lies between the vectors of line L6. If k<Kk < K, Lemma 2 applied to each coordinate shows that the activation lies between the vectors of line L8. If k=Kk = K, there is no ReLU and the claim is the bound of line L6. Each box keeps l(k)≤u(k)l^{(k)} \le u^{(k)}, because r≥0r \ge 0 and the ReLU is nondecreasing, so the induction can go on. □\square

Theorem 2 (the certificate). Let x∈[0,1]dx \in [0,1]^d, ϵ≥0\epsilon \ge 0 and yy be a label. If CERTIFY-IBP returns true, then for every x′∈S=B∞(x,ϵ)∩[0,1]dx' \in S = B_\infty(x, \epsilon) \cap [0,1]^d and every j≠yj \ne y, zy(x′)>zj(x′)z_y(x') > z_j(x'), so yy is the only argmax of z(x′)z(x').

Proof. Line L10 gives li=max⁡(xi−ϵ,0)l_i = \max(x_i - \epsilon, 0) and ui=min⁡(xi+ϵ,1)u_i = \min(x_i + \epsilon, 1). A point x′x' is in SS if and only if l≤x′≤ul \le x' \le u, since the two interval conditions on each coordinate intersect to [li,ui][l_i, u_i]. Line L11 changes only the last layer: its output number jj is now (WK[y]−WK[j])a+bK[y]−bK[j]=zy−zj(W_K[y] - W_K[j]) a + b_K[y] - b_K[j] = z_y - z_j, where aa is the last hidden activation. The hidden layers are the same, so this new network computes the vector of margins. By Theorem 1, every x′∈Sx' \in S has zy(x′)−zj(x′)≥lj′z_y(x') - z_j(x') \ge l'_j. Line L13 returns true only when every lj′>0l'_j > 0, so every margin is positive on SS. □\square

Theorem 3 (one layer is tight). If K=1K = 1, each bound of line L9 is reached at a corner of the input box, so the output box is the smallest box that contains the image of the input box.

Proof. With K=1K = 1 the loop runs once with no ReLU. Line L3 gives the center and radius of the input box, and Lemma 1 shows that the end li′l'_i is reached at the corner vt=μt−sign⁡(Wit)rtv_t = \mu_t - \operatorname{sign}(W_{it}) r_t and the end ui′u'_i at vt=μt+sign⁡(Wit)rtv_t = \mu_t + \operatorname{sign}(W_{it}) r_t; both corners are in the box. So no smaller interval contains all the values of output ii, for each ii. With hidden layers this fails in general, because Lemma 1 treats the coordinates of the activation as independent, while they all depend on the same input; the worked example on the page has the bound −1.25-1.25 against the true minimum 11. ■\blacksquare

Complexity

  • Time. Each layer costs one product with WkW_k (line L4) and one with ∣Wk∣|W_k| (line L5), so the total is Θ(N+d)\Theta(N + d) for NN weights, about twice a forward pass. Line L11 costs O(kh)O(k h) for the last layer with hh inputs.
  • Space. Θ(n+d)\Theta(n + d) besides the weights, for the center and the radius of the current layer.
  • Training. In IBP training the bounds are part of the loss, so a training step costs about as much as a step of normal training with two extra passes.

Properties

  • Sound, not complete. A certificate is a proof (a theorem). A failure says nothing, as in the example.
  • A lower bound on robust accuracy. The fraction of test points that IBP certifies is a lower bound on the robust accuracy, and an attack such as the PGD attack gives an upper bound.
  • Exact for one layer. For one affine layer, or a network whose hidden units are all stable on the box, the bound of each output alone is tight.
  • Monotone in the box. A smaller input box gives smaller or equal output boxes, so the certified radius is well defined and can be found by bisection.
  • Loose for deep networks. The width grows by a factor of about ∥∣Wk∣∥\lVert |W_k| \rVert per layer and ignores all correlations between units, so for a network trained without IBP the bounds are often useless after a few layers (a measurement in the papers below).

Variants and improvements

  • IBP training. Gowal et al. (2018) minimize κ L(z(x),y)+(1−κ) L(z^,y)\kappa\, L(z(x), y) + (1 - \kappa)\, L(\hat z, y), where z^\hat z is the worst-case logit vector built from the lower bounds of the margins. Training ramps ϵ\epsilon up from 0 and κ\kappa down from 1, so the network learns to keep its bounds tight. Networks trained this way are often certified by IBP itself.
  • Abstract domains. IBP is abstract interpretation with the interval domain. Mirman, Gehr and Vechev (2018) also train with zonotopes, which keep linear correlations.
  • Linear bounds. Linear bound propagation (CROWN and its relatives) bounds each unit by linear functions of the input. It is usually tighter and costs more. CROWN-IBP uses IBP for the hidden layers and a linear bound for the last layer, as a cheaper middle ground.
  • Complete verification. IBP bounds are the first step of branch-and-bound verifiers and the bound tightening step of Reluplex and of mixed integer programming encodings: a unit whose interval does not contain 0 needs no case split.

When to use it

Use IBP as the cheapest sound check, to decide quickly that many points are safe, to tighten bounds before an exact verifier, and above all to train networks that are certifiable. Do not use it to verify a network trained without it: the bounds are usually too loose, and a linear bound or an exact method is needed. For large ℓ2\ell_2 radii on large models, randomized smoothing gives a different, probabilistic certificate.

Pitfalls

  • Bounds from the ends instead of the center. Computing Wl+bW l + b and Wu+bW u + b at lines L4 and L5 is wrong as soon as WW has a negative entry: the "lower" bound can be above the "upper" bound, and the result is not sound. Use the center and radius form, or split WW into its positive and negative parts.
  • Bounding the logits apart. Without line L11, the check z‾y>z‾j\underline z_y > \overline z_j ignores that zyz_y and zjz_j depend on the same hidden units. It is still sound but looser than the margin bound. Fold the margins into the last layer.
  • Floating point. Lines L4 to L6 in floats can round a bound inward. A certificate meant as a proof must round outward, or use exact rational arithmetic. The code of this page uses plain floats, so its tests compare with a small tolerance.
  • The box outside the valid range. If line L10 does not cut the box to [0,1]d[0,1]^d, the certificate covers more points than the threat model asks for and fails more often. It is not wrong, only weaker.
  • A ReLU after the last layer. If line L7 also applies a ReLU after layer KK, the margin bounds are cut at 0 and lose their meaning as logits.

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 table and the radius 5/365/36, that a point box gives the forward pass, that one affine layer is tight at the corners, and soundness on 500 random networks against the exact range from an enumeration of all activation patterns and against dense sampling. They also check that nested boxes give nested bounds 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.

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

"""Interval bound propagation (IBP) for feed-forward ReLU networks.

A network is a list of affine layers (W, b). A ReLU follows every layer except the
last one, so the logits are z = W_K relu(... relu(W_1 x + b_1) ...) + b_K. IBP pushes
a box through the layers in center and radius form. The bounds hold for every input
of the box, in exact arithmetic. With floats they can be off by rounding; a verifier
that must be sound on floats rounds outward (interval arithmetic).

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

from typing import Sequence

Vector = 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 logits of the network 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 interval_bound_propagation(layers: Sequence[Layer], lower: Sequence[float], upper: Sequence[float]) -> tuple[Vector, Vector]:
    """Lower and upper bounds of the outputs of the last layer over the box [lower, upper].

    Precondition: lower[j] <= upper[j] for every input j, and the layer sizes match.
    Every output f(x) of the network for x in the box satisfies l <= f(x) <= u.
    Cost O(N) for N weights in total, one matrix-vector product per layer for the
    center and one for the radius.
    """
    lo, hi = list(lower), list(upper)  # @line L1
    last = len(layers) - 1
    for k, (w, b) in enumerate(layers):  # @line L2
        mu = [(h + l) / 2.0 for l, h in zip(lo, hi, strict=True)]  # @line L3
        r = [(h - l) / 2.0 for l, h in zip(lo, hi, strict=True)]  # @line L3
        mu2 = [sum(wi * m for wi, m in zip(row, mu, strict=True)) + bi for row, bi in zip(w, b, strict=True)]  # @line L4
        r2 = [sum(abs(wi) * s for wi, s in zip(row, r, strict=True)) for row in w]  # @line L5
        lo = [m - s for m, s in zip(mu2, r2, strict=True)]  # @line L6
        hi = [m + s for m, s in zip(mu2, r2, strict=True)]  # @line L6
        if k < last:  # @line L7
            lo = [max(v, 0.0) for v in lo]  # @line L8
            hi = [max(v, 0.0) for v in hi]  # @line L8
    return lo, hi  # @line L9


def margin_layers(layers: Sequence[Layer], y: int) -> list[Layer]:
    """Fold the margins z_y - z_j, for j != y, into the last layer. Cost O(k h)."""
    w, b = layers[-1]
    rows = [[a - c for a, c in zip(w[y], w[j], strict=True)] for j in range(len(w)) if j != y]
    consts = [b[y] - b[j] for j in range(len(b)) if j != y]
    return [*layers[:-1], (rows, consts)]


def input_box(x: Sequence[float], epsilon: float) -> tuple[Vector, Vector]:
    """The box B_infinity(x, epsilon) intersected with [0, 1]^d. Cost O(d)."""
    return [max(a - epsilon, 0.0) for a in x], [min(a + epsilon, 1.0) for a in x]


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

    Returns (certified, l) with l the lower bounds of the margins z_y - z_j, j != y,
    in the order of j. A True answer is a proof in exact arithmetic; a False answer
    proves nothing. Precondition: epsilon >= 0, x in [0, 1]^d, 0 <= y < k.
    Cost O(N) for N weights in total.
    """
    lower, upper = input_box(x, epsilon)  # @line L10
    spec = margin_layers(layers, y)  # @line L11
    lo, _ = interval_bound_propagation(spec, lower, upper)  # @line L12
    return all(v > 0.0 for v in lo), lo  # @line L13
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_interval_bound_propagation.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/interval-bound-propagation/. The authors are listed in prov/2WWJMG.jsonl.

"""Tests of interval bound propagation on seeded synthetic ReLU networks only."""

import itertools
import random

import mlkit as m
from interval_bound_propagation import (
    certify_ibp,
    forward,
    input_box,
    interval_bound_propagation,
    layers_from_net,
    margin_layers,
)

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 exact_range(layers, lower, upper):
    """Exact (min, max) of the single 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
        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 = a[0][0] * x0 + a[0][1] * x1 + c[0]
                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_table():
    lower, upper = input_box([0.5, 0.5], 0.25)
    assert lower == [0.25, 0.25] and upper == [0.75, 0.75]
    l1, u1 = interval_bound_propagation(EXAMPLE[:1], lower, upper)
    assert l1 == [-0.25, -0.75] and u1 == [1.25, 0.75]
    l2, u2 = interval_bound_propagation(EXAMPLE, lower, upper)
    assert l2 == [0.25, -2.5] and u2 == [2.25, 1.5]
    ok, lo = certify_ibp(EXAMPLE, [0.5, 0.5], 0, 0.25)
    assert not ok and abs(lo[0] + 1.25) < TOL
    lo_ex, _ = exact_range(margin_layers(EXAMPLE, 0), lower, upper)
    assert abs(lo_ex - 1.0) < 1e-9
    ok, lo = certify_ibp(EXAMPLE, [0.5, 0.5], 0, 0.1)
    assert ok and abs(lo[0] - 0.7) < TOL


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


def test_point_box_gives_the_forward_value():
    rng = random.Random(5)
    for _ in range(50):
        layers = random_layers(rng, [3, 4, 2])
        x = [rng.random() for _ in range(3)]
        lo, hi = interval_bound_propagation(layers, x, x)
        z = forward(layers, x)
        assert all(abs(a - b) < TOL and abs(c - b) < TOL for a, b, c in zip(lo, z, hi))


def test_one_affine_layer_is_tight():
    rng = random.Random(6)
    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]
        lo, hi = interval_bound_propagation(layers, 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
            assert abs(hi[i] - max(v[i] for v in corners)) < 1e-9


def test_mlkit_network_conversion():
    rng = random.Random(7)
    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)
    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 = input_box(x, epsilon)
        spec = margin_layers(layers, y)
        lo, hi = interval_bound_propagation(spec, lower, upper)
        j = rng.randrange(len(lo))
        one = [*spec[:-1], ([spec[-1][0][j]], [spec[-1][1][j]])]
        ex_lo, ex_hi = exact_range(one, lower, upper)
        assert lo[j] <= ex_lo + 1e-9 and ex_hi <= hi[j] + 1e-9
        for _ in range(30):
            p = [rng.uniform(a, b) for a, b in zip(lower, upper)]
            v = forward(spec, p)
            assert all(l - 1e-9 <= a <= u + 1e-9 for l, a, u in zip(lo, v, hi))
            assert ex_lo - 1e-9 <= v[j] <= ex_hi + 1e-9
        ok, _ = certify_ibp(layers, x, y, epsilon)
        if ok:
            assert ex_lo > 0.0


def test_nested_boxes_give_nested_bounds():
    rng = random.Random(9)
    for _ in range(200):
        layers = random_layers(rng, [3, 4, 3, 2])
        lower = [rng.uniform(0, 0.4) for _ in range(3)]
        upper = [a + rng.uniform(0, 0.4) for a in lower]
        inner_lo = [a + rng.uniform(0, 1) * (b - a) / 2 for a, b in zip(lower, upper)]
        inner_hi = [max(c, b - rng.uniform(0, 1) * (b - a) / 2) for a, b, c in zip(lower, upper, inner_lo)]
        lo, hi = interval_bound_propagation(layers, lower, upper)
        lo2, hi2 = interval_bound_propagation(layers, inner_lo, inner_hi)
        assert all(a <= b + 1e-9 and c <= d + 1e-9 for a, b, c, d in zip(lo, lo2, hi2, hi))


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_ibp(layers, x, y, 0.02)
        if ok:
            count += 1
            lower, upper = input_box(x, 0.02)
            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

Interval arithmetic is old, and abstract interpretation with intervals goes back to Cousot and Cousot in 1977. Its use for neural networks came with the search for certificates after adversarial examples were found. Gehr et al. (2018) verified networks with abstract interpretation in the AI2 system, and Mirman, Gehr and Vechev (ICML 2018) made the abstract domains differentiable, so that a network could be trained to make its own bounds tight. Gowal et al. posted "On the effectiveness of interval bound propagation for training verifiably robust models" in October 2018. They showed that the simplest domain, intervals, gives strong verified accuracy when the training schedule is chosen with care, at a small cost per step. IBP training then became a common baseline for certified training, and later work such as CROWN-IBP mixed it with linear bounds.

References

  1. Sven Gowal, Krishnamurthy Dvijotham, Robert Stanforth, Rudy Bunel, Chongli Qin, Jonathan Uesato, Relja Arandjelovic, Timothy Mann and Pushmeet Kohli, On the effectiveness of interval bound propagation for training verifiably robust models, arXiv 2018 (a later version appeared at ICCV 2019 as Scalable verified training for provably robust image classification), the interval bounds in center and radius form, the margin specification folded into the last layer, and the training loss with the schedules for epsilon and kappa
  2. Matthew Mirman, Timon Gehr and Martin Vechev, Differentiable abstract interpretation for provably robust neural networks, ICML 2018, PMLR 80, pages 3578 to 3586, training through the box domain and the zonotope domain of abstract interpretation
  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 linear relaxation that gives tighter bounds than intervals, for comparison
  4. 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, the difference between a certified lower bound and an attack upper bound on robust accuracy
  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

Where this leads

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