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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 can have both signs on the box, with bounds , is replaced by two lines: the chord above it and a line with 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 .
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 , a ReLU after every layer except the last, and the pre-activations , , . Given a box and a matrix , compute a vector with for every in the box. For robustness at with label , the rows of are for , the box is , and the point is certified when every entry of is positive. This is a relaxation of the neural network verification problem, which is NP-complete.
The algorithm
LBP-BACKWARD(layers, k, Λ, l, u) ▷ a lower bound of Λ z_k(x) for l <= x <= u- 1
A ← Λ, c ← 0 ▷ the bound so far is A z_j + c - 2
for j ← k downto 1 do - 3
c ← c + A b_j - 4
A ← A W_j ▷ now the bound is A a_{j-1} + c - 5
if j > 1 then ▷ a_{j-1} = relu(z_{j-1}), z_{j-1} in [l_{j-1}, u_{j-1}] - 6
for each unit i of layer j - 1 do - 7
(s+, t+, s-, t-) ← RELAX(l_{j-1,i}, u_{j-1,i}) - 8
for each row r of A do - 9
if A[r, i] >= 0 then c_r ← c_r + A[r, i] t-, A[r, i] ← A[r, i] s- - 10
else c_r ← c_r + A[r, i] t+, A[r, i] ← A[r, i] s+ - 11
m_r ← c_r + sum over t of A[r, t] · (l_t if A[r, t] >= 0 else u_t), for each row r - 12
return m LBP(layers, l, u, Λ)- 13
for k ← 1 to K - 1 do - 14
l_k ← LBP-BACKWARD(layers, k, I, l, u), u_k ← -LBP-BACKWARD(layers, k, -I, l, u) - 15
return LBP-BACKWARD(layers, K, Λ, l, u)
RELAX returns the slope and intercept of the upper line and of the lower line of the ReLU on . If both lines are . If both are the identity. Otherwise the upper line is the chord, and , and the lower line is with if and if not, the adaptive choice of CROWN. Any 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 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: , , , , the point with and label , and . The margin is , so times the last layer has the row and the constant .
Lines L13 and L14 give the first-layer bounds and , the same as the intervals, since one affine layer is exact. Both units are unstable.
| unit | upper line | lower line () | coefficient | line used | |
|---|---|---|---|---|---|
| 1 | (, so ) | lower (L9) | |||
| 2 | (, so ) | upper (L10) |
The backward pass for at : line L3 gives and line L4 gives . Line L9 keeps , and line L10 turns into , so and . In the next round line L3 adds , so , and line L4 gives . The bound is : the input cancels. Line L11 puts and gives , so the point is certified.
Interval bound propagation gives on the same box and fails, and the exact minimum is . For the bound is (it is at , equal to the exact minimum), and the same formula holds up to , which is the radius that this method certifies. Interval bounds certify and the exact radius is .
Correctness
Theorem (soundness). If the bounds used by RELAX contain every pre-activation for in the box, then the vector of line L12 satisfies for every 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 changes the label.
The proof keeps the invariant for every in the box, where is at the top of round and after line L4. Lines L3 and L4 are an identity, because . Line L9 uses for , and line L10 uses for ; both follow from the two lines of RELAX, which lie below and above the ReLU on . 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 , pre-activations , activations for , and . The box is . Inequalities between vectors hold in each coordinate, and arithmetic is exact.
Lemma 1 (the two lines). Let and let RELAX. For every ,
Proof. If , then on and both lines are . If , then and both lines are . Otherwise . The upper line is the chord through and . The ReLU is convex, so on it lies below its chord between the two ends. The lower line is with . For , since , and for , since . The same argument works for any .
Lemma 2 (minimum of a linear function over a box). For a row vector and a number , .
Proof. The sum has one term per coordinate, and the coordinates range independently over . A term with is smallest at , and a term with is smallest at . The point that makes every term smallest is in , so it attains the minimum.
Theorem 1 (soundness of one backward pass). Suppose that for every and every , . Then LBP-BACKWARD returns with for every .
Proof. Fix and one row . We show the invariant: at the top of round of line L2, , and after line L10 of round , .
At the start (), line L1 gives and , so the invariant is an equality. Lines L3 and L4 replace by and by . Since , the value equals , so the inequality carries over to the form in . If , this is the form in , and the loop ends.
If , then and by hypothesis . Lines L6 to L10 treat one unit at a time, and each step changes only column of and the constant . Let be the lines of unit . If , Lemma 1 gives , which is line L9. If , multiplying the upper line by a negative number gives , 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 multiplies for every , which is the invariant at the top of round .
When the loop ends, for every . Line L11 computes by Lemma 2, which is at most for each . So .
Theorem 2 (soundness of LBP and of the certificate). LBP returns with for every . If has the rows for , the box is , and every entry of is positive, then is the only argmax of for every in the box.
Proof. By induction on in line L13. Assume that the bounds of the layers are sound (for there is nothing to assume). Theorem 1 with gives , and with it gives LBP-BACKWARD, that is . So the bounds of layer are sound. After the loop, the hypothesis of Theorem 1 holds for , and line L15 gives the claim. For the certificate, for every .
Theorem 3 (exact on stable networks). If and every unit of the hidden layer has or , then .
Proof. For , the bounds of line L14 for come from one affine layer with no ReLU, so they are the exact minimum and maximum of each over by Lemma 2. If , then on and both lines are ; if , then and both lines are the identity. So every step of lines L9 and L10 is an equality for every , and the loop ends with on . Line L11 is the exact minimum by Lemma 2.
Complexity
- Time. One backward pass from layer with rows costs for lines L3 and L4 over all layers, plus per ReLU layer. Line L14 runs it with rows for every hidden layer, so the total is , plus for line L11. This is about times more than interval bounds.
- Space. The matrix has rows and at most columns, so , plus for the stored bounds.
- Cheaper forms. Bounding only the last layer with linear bounds and the hidden layers with intervals (CROWN-IBP) costs for 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 , the bound is not always above the interval bound. On 2000 random networks with 2 inputs and 2 to 6 hidden units at , 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 (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, and , which makes the two lines parallel.
- Optimized slopes. The lower slope of each unit can be any number in . 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 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 , 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 with outside , or the chord used as a lower line with a nonzero intercept, crosses above the ReLU on part of .
- Expecting it to beat intervals every time. As the properties above show, the adaptive 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 , 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| 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 2XBS61 Edit this page History Report an error Markdown