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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and radius into the box with center and radius , and a ReLU maps an interval to . To certify that a classifier keeps the label on , IBP bounds the margins 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 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 .
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 in , an input with label and a radius . Let . The verification question of the neural network verification problem is whether for every and every . IBP answers a weaker question: it computes numbers with , and it reports "certified" when every .
The algorithm
IBP(layers (W_1, b_1) .. (W_K, b_K), l, u) ▷ the box l <= x <= u- 1
l, u ← the input box - 2
for k ← 1 to K do - 3
mu ← (u + l)/2, r ← (u - l)/2 ▷ center and radius - 4
mu ← W_k mu + b_k - 5
r ← |W_k| r ▷ |W_k| takes the absolute value of each entry - 6
l ← mu - r, u ← mu + r - 7
if k < K then ▷ a ReLU follows every layer but the last - 8
l ← max(l, 0), u ← max(u, 0) - 9
return (l, u) CERTIFY-IBP(layers, x, y, epsilon)- 10
l ← max(x - epsilon, 0), u ← min(x + epsilon, 1) - 11
replace (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 - 12
(l', u') ← IBP(layers, l, u) - 13
return 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 is largest in coordinate when each has the sign of . 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 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 , two hidden ReLUs and two logits, with , , , . At the hidden layer is and the logits are , so . Line L11 gives the margin , where . Take , so the box of line L10 is .
| step | center | radius | lower | upper |
|---|---|---|---|---|
| input (L1, L3) | ||||
| layer 1 (L4 to L6) | ||||
| ReLU (L8) | ||||
| margin layer (L3 to L6) |
The lower bound is negative, so IBP does not certify the point at . The point is robust all the same: the true minimum of over the box is , which Reluplex proves exactly and linear bound propagation bounds from below by . The loss comes from line L5 in the margin layer: the radius treats and as free to move in opposite directions, while both depend on the same two inputs.
At both hidden bounds are and , and the margin bound is , so IBP certifies. For the first hidden unit stays positive on the box, and the bound is . It is positive exactly when , so that is the radius that IBP certifies. The exact robust radius of this point is .
Correctness
Theorem (soundness). If on input, then for every with , the output of the layers satisfies for the pair of line L9. So if CERTIFY-IBP returns true, then for every and every .
The proof is an induction on the layers. If for every , then , which is lines L4 to L6. The ReLU is nondecreasing, so gives , 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 , with a ReLU after every layer except the last. We write for the output of layer at the input , and we compare vectors coordinate by coordinate. Arithmetic is exact.
Lemma 1 (an affine layer). Let be vectors with , and let satisfy for every . Then for every row ,
Both ends are reached: the upper one at , the lower one at .
Proof. . By the triangle inequality, . At the given points every term equals with the same sign for all , so the bound is an equality.
Lemma 2 (a ReLU). If , then , and both ends are reached on .
Proof. The function is nondecreasing, which gives the inequalities. It is continuous, so by the intermediate value theorem it takes every value between and on ; in particular it takes the two ends, at and .
Theorem 1 (soundness of IBP). Let be the input box of line L1, and let be the box after layer in the loop of lines L2 to L8. For every input with , the activation of layer (after its ReLU when ) satisfies . In particular the pair of line L9 bounds .
Proof. By induction on . For the claim is the hypothesis . Assume the claim for . Line L3 sets and , so is the same as for every . By Lemma 1, the pre-activation lies between the vectors of line L6. If , Lemma 2 applied to each coordinate shows that the activation lies between the vectors of line L8. If , there is no ReLU and the claim is the bound of line L6. Each box keeps , because and the ReLU is nondecreasing, so the induction can go on.
Theorem 2 (the certificate). Let , and be a label. If CERTIFY-IBP returns true, then for every and every , , so is the only argmax of .
Proof. Line L10 gives and . A point is in if and only if , since the two interval conditions on each coordinate intersect to . Line L11 changes only the last layer: its output number is now , where is the last hidden activation. The hidden layers are the same, so this new network computes the vector of margins. By Theorem 1, every has . Line L13 returns true only when every , so every margin is positive on .
Theorem 3 (one layer is tight). If , 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 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 is reached at the corner and the end at ; both corners are in the box. So no smaller interval contains all the values of output , for each . 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 against the true minimum .
Complexity
- Time. Each layer costs one product with (line L4) and one with (line L5), so the total is for weights, about twice a forward pass. Line L11 costs for the last layer with inputs.
- Space. 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 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 , where is the worst-case logit vector built from the lower bounds of the margins. Training ramps up from 0 and 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 radii on large models, randomized smoothing gives a different, probabilistic certificate.
Pitfalls
- Bounds from the ends instead of the center. Computing and at lines L4 and L5 is wrong as soon as 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 into its positive and negative parts.
- Bounding the logits apart. Without line L11, the check ignores that and 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 , 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 , 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 , 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 2WWJMG Edit this page History Report an error Markdown