Algorithmresearch
Krum
Also called Krum aggregation rule.
A Byzantine-robust aggregation rule that needs n > 2f + 2 and picks the update with the smallest sum of squared distances to its n - f - 2 nearest updates.
- Time
- O(n^2 (d + log n)) worst
- Space
- O(n) extra
- Where
- d = the dimension of an update; f = the largest number of Byzantine updates; n = the number of updates
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peva Blanchard, El Mahdi El Mhamdi, Rachid Guerraoui, Julien Stainer, 2017
Krum is an aggregation rule for distributed training with a parameter server: clients each send an update vector (a gradient estimate), at most of them are Byzantine and may send anything, and the server must pick a vector to step with. Krum gives each update the score , the sum of the squared distances from to its nearest other updates, and returns the update with the smallest score. It is defined only when . Blanchard, El Mhamdi, Guerraoui and Stainer (2017) proposed it and proved that, when the honest updates are i.i.d. and their spread is small next to the true gradient, the chosen vector still points in a descent direction. The plain average fails against one Byzantine client.
In plain words
Many workers each send a suggestion for the next step. Most are honest, but a few may lie, and the liars may work together. If you take the average, one liar can send a huge vector and drag the average anywhere.
Krum asks each suggestion a question: how close are you to your nearest neighbors? It counts only the closest neighbors, as many as it can be sure include mostly honest ones, and adds up the squared distances to them. Then it picks the suggestion with the smallest total, the one that sits in the tightest group.
A liar far away has a large total, so it is not picked. A liar can still be picked if it sits right among the honest suggestions, but then it is close to an honest one, so it cannot do much harm.
The problem
The threat model, in the three parts of Biggio and Roli:
- Goal of the attacker. Stop the training from converging, or bias the model.
- Knowledge. Full. Blanchard et al. let the Byzantine clients know the rule, the data and the updates of all other clients, and collude.
- Capability. Control at most of the updates in each round, with arbitrary values. The server is trusted, and the honest updates are i.i.d. unbiased estimates of the gradient .
Input. Vectors and an integer with .
Output. One of the input vectors, , where minimizes
with ties broken toward the smallest index, as Blanchard et al. do. The sum of the smallest of the distances from is this minimum.
Why . Each update has others. Leaving out of them makes sure that at least one honest update is among those left out, so every Byzantine neighbor of an honest update is no farther than some honest update. And is what says: the neighbor set of any update holds more updates than there are Byzantine ones, so at least of them are honest, whether or not the update itself is honest. The proof of Proposition 1 of Blanchard et al. divides by this count. Whether the condition is tight is left open in their Section 7.
The algorithm
KRUM(V_1, ..., V_n, f)- 1
if n <= 2f + 2 then fail - 2
for i = 1 to n do - 3
D <- [ ||V_i - V_j||^2 for every j != i ] - 4
sort D in increasing order - 5
s(i) <- D[1] + ... + D[n - f - 2] - 6
if s(i) < best score so far then i* <- i - 7
return V_{i*}
Line L1 rejects inputs where the guarantee cannot hold. Lines L3 to L5 compute the score: the squared distances, sorted, and the sum of the first . Line L6 keeps the first index of smallest score, because the test is strict. Line L7 returns an input vector, never a new one.
m-Krum. Section 6 of the arXiv version picks updates by running Krum, removing the winner and running again, and averages the winners. Each round must be valid, so ; the paper states the condition as .
Example
One coordinate, , , so each score sums the smallest squared distances. The updates are , and is Byzantine.
| squared distances to the others | two smallest | |||
|---|---|---|---|---|
| 1 | 0 | 1, 4, 16, 100 | 1, 4 | 5 |
| 2 | 1 | 1, 1, 9, 81 | 1, 1 | 2 |
| 3 | 2 | 4, 1, 4, 64 | 1, 4 | 5 |
| 4 | 4 | 16, 9, 4, 36 | 4, 9 | 13 |
| 5 | 10 | 100, 81, 64, 36 | 36, 64 | 100 |
Krum returns . The average is , already pulled toward the Byzantine value; with the average would be , and Krum would still return .
Now let the Byzantine client send instead. Its squared distances are , so its score is , and the score of becomes . Krum picks the Byzantine vector. But it lies between two honest updates, and the bound of the next section caps the harm: here (the honest update is within squared distance of every honest update), and the chosen vector must be within squared distance of some honest update. It is within .
Correctness
The computation. The sum of the smallest entries of is the minimum over all sets of that size, so line L5 computes exactly and line L6 returns the first minimizer.
Theorem (a deterministic bound, proved on this page). Let be the set of honest indices, with at most Byzantine indices and , and let . Then
The idea, from the proof of Proposition 1 of Blanchard et al.: an honest has at least honest others, so ; a Byzantine has at most Byzantine others, so at least of its nearest are honest, and . Combine with . The full proof is in the proof file.
Theorem (Blanchard et al. 2017, Proposition 1, cited). If the honest updates are i.i.d. with mean and , and , then Krum is -Byzantine resilient with : , and the moments of order 2 to 4 of the output are bounded by those of . Here
which is when grows with and when is fixed. Their Section 5 turns this into almost sure convergence of the gradient norm to a region where .
Proof: Krum returns the update of smallest score, and that update is close to an honest onefull
Setting. The input is and an integer with . Write , so . For let . The score is
Claim 1 (the computation). Line L5 sets to this minimum, and line L7 returns where is the smallest index with .
Proof. Line L3 builds the list of the values , , and line L4 sorts it, so that . Let be any set of indices other than , and list its values in increasing order as . For each , at least entries of are at most (the values themselves), so . Summing over gives . The first entries of are themselves the values of one such set . So line L5 computes the minimum . Line L6 replaces the current index only on a strict decrease, so after the loop of line L2 the kept index is the first index whose score equals the minimum, and line L7 returns its vector. Line L1 rejects every input with , so no other input reaches lines L2 to L7.
Claim 2 (closeness to an honest update). Let be a set of honest indices whose complement has . Let
Then the index returned by Krum satisfies
Proof. If , the left side is and there is nothing to prove. So let , and let be an index that attains , so that for every .
Upper bound on . The honest indices other than number . Take any of them as the set in the definition of . Each term is at most , so .
Lower bound on . Let be a set of indices other than that attains . The Byzantine indices other than number , so holds at least honest indices. This count is positive because . Let . Each honest has , and every term is nonnegative, so .
Combination. By Claim 1, . Hence , and dividing by the positive number gives the claim.
Remarks. The bound does not depend on the values of the Byzantine updates, on the dimension, or on any probability model; it is the deterministic core of the proof of Proposition 1 of Blanchard et al. (arXiv:1703.02757v1, Section 4), with the count that holds for a Byzantine winner in place of their count , which holds for any index. The argument of Claim 2 uses only , that is ; Krum itself, as defined by Blanchard et al. and in line L1, requires . The constant grows with the spread of the honest updates, which in dimension with per-coordinate noise is of order ; the claim therefore says that the damage of a Byzantine winner is at most a constant times the honest noise, not that it is small.
Complexity
- Time. Each of the updates needs distances at each (line L3) and a sort of numbers (line L4), so the total is , Lemma 2 of Blanchard et al. A selection algorithm such as quickselect in place of the sort gives expected time. Computing each distance once and storing the matrix halves the distance work and costs space.
- Space. extra for the list of one row, beyond the input.
- m-Krum. runs of Krum, so .
Properties
- Output is an input. Krum returns one of the and never averages, so its variance is that of a single update. m-Krum trades some robustness for a lower variance.
- Not linear. Lemma 1 of Blanchard et al. shows that any rule with nonzero can be moved to any vector by one Byzantine update . Krum escapes this because a far update gets a large score.
- Deterministic and order dependent only through ties. A permutation of the inputs changes the output only when two scores are equal.
- Breakdown. The rule tolerates Byzantine updates, close to the bound of the median.
Variants and improvements
- m-Krum (Blanchard et al., Section 6). Average winners of repeated Krum. The paper also mentions taking the best scores of one run and leaves its resilience open.
- Coordinate-wise median and trimmed mean (Yin et al. 2018). Aggregate each coordinate with the median or the trimmed mean; they prove error rates that are optimal in their statistical model, and the cost is expected for the median by selection.
- Bulyan (El Mhamdi et al. 2018). Select updates by repeated Krum, then take a coordinate-wise trimmed mean around the median; it needs and limits the drift per coordinate that Krum allows in high dimension.
- Geometric median. The point that minimizes the sum of distances, a robust center that is not an input; see geometric median.
When to use it
Use Krum when the honest updates are close to i.i.d. and the noise is small next to the gradient, which is the setting of its theorem, and when is small enough that distance computations per round are cheap. Prefer the coordinate-wise median or trimmed mean when is large and is large, since they cost . With clients whose data differ (non-i.i.d. federated data), honest updates are far apart, the score of an honest outlier client is large, and Krum may ignore the same honest clients every round; then the guarantee does not hold, and the rule biases the model against those clients. None of these rules is a defense against a small targeted change such as a backdoor that stays inside the honest spread.
Pitfalls
- Distances that are not squared. Line L3 must use . The proofs of Blanchard et al. use squared distances, and so does the bound above; a variant with plain distances is a different rule with no proof here.
- Counting the update itself. Line L5 sums distances to other updates. Sorting all distances, including the zero distance to itself, and then summing values sums one other too few. Lemma 2 of Blanchard et al. sums values for this reason, since that list includes the zero.
- Skipping the size check. Line L1 must reject , the range where the theorem of Blanchard et al. does not apply. For the rule fails outright: then , so colluders that send the same vector have only each other among their nearest, get score and win.
- Ignoring attacks inside the spread. The bound limits the distance to the honest updates in terms of their spread . Baruch et al. (2019) choose Byzantine updates that move each coordinate by a fraction of the honest standard deviation in the same direction every round; this stays within the bound and still biases training. In high dimension the spread grows like , which is the weakness that Bulyan addresses.
- Treating the score of one round as an identity. Krum gives no list of Byzantine clients. An honest client with unusual data looks the same as a Byzantine one.
Implementations
The code runs only on update vectors that the tests build from a fixed seed, from Gaussian draws and from the logistic gradients of mlkit on synthetic blobs; it never talks to a client or a network. The tests compare the scores and the choice with brute force over every set of other updates on 600 random inputs (half of them with small integers, so that ties occur), check m-Krum against repeated brute force, check the distance bound of the theorem against four abstract Byzantine strategies, check Lemma 1 for the average, and run 40 rounds of training with 2 Byzantine clients out of 9.
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/krum-aggregation/. The authors are listed in prov/NQC1A8.jsonl.
"""Krum, the Byzantine-robust aggregation rule of Blanchard, El Mhamdi, Guerraoui and Stainer (2017).
The input is a list of n update vectors, of which at most f may be Byzantine. The tests
build every update from a fixed seed; nothing here talks to a client or a network.
"""
import math
from typing import Sequence
Vector = list[float]
def squared_distance(u: Sequence[float], v: Sequence[float]) -> float:
"""The squared Euclidean distance ||u - v||^2, correctly rounded by math.fsum. Cost O(d)."""
return math.fsum((a - b) * (a - b) for a, b in zip(u, v, strict=True))
def check_sizes(n: int, f: int) -> None:
"""Raise ValueError unless f >= 0 and n > 2 f + 2, the condition under which Krum is defined."""
if f < 0 or n <= 2 * f + 2:
raise ValueError("Krum needs f >= 0 and n > 2 f + 2")
def krum_scores(updates: Sequence[Sequence[float]], f: int) -> list[float]:
"""The score s(i): the sum of the n - f - 2 smallest squared distances from V_i to the other updates.
Precondition: n > 2 f + 2 and all updates have the same length d.
Cost O(n^2 (d + log n)) time and O(n) extra space.
"""
n = len(updates)
check_sizes(n, f)
m = n - f - 2
scores: list[float] = []
for i in range(n):
dists = sorted(squared_distance(updates[i], updates[j]) for j in range(n) if j != i)
scores.append(math.fsum(dists[:m]))
return scores
def krum_index(updates: Sequence[Sequence[float]], f: int) -> int:
"""The index i* of the update with the smallest score; ties go to the smallest index.
Precondition: n > 2 f + 2 and all updates have the same length d.
Cost O(n^2 (d + log n)) time and O(n) extra space.
"""
n = len(updates)
if f < 0 or n <= 2 * f + 2: # @line L1
raise ValueError("Krum needs f >= 0 and n > 2 f + 2")
m = n - f - 2
best, best_score = -1, math.inf
for i in range(n): # @line L2
dists = [squared_distance(updates[i], updates[j]) for j in range(n) if j != i] # @line L3
dists.sort() # @line L4
score = math.fsum(dists[:m]) # @line L5
if score < best_score: # @line L6
best, best_score = i, score
return best # @line L7
def krum(updates: Sequence[Sequence[float]], f: int) -> Vector:
"""The update V_{i*} chosen by Krum, as a new list. Same precondition and cost as krum_index."""
return list(updates[krum_index(updates, f)])
def multi_krum_indices(updates: Sequence[Sequence[float]], f: int, m: int) -> list[int]:
"""The m-Krum selection of arXiv:1703.02757v1, Section 6: pick by Krum, remove, repeat m times.
Returns the original indices in the order they were picked. Precondition: 1 <= m and
every round is valid, that is n - m + 1 > 2 f + 2. Cost O(m n^2 (d + log n)).
"""
n = len(updates)
if m < 1 or n - m + 1 <= 2 * f + 2 or f < 0:
raise ValueError("m-Krum needs m >= 1 and n - m + 1 > 2 f + 2")
left = list(range(n))
picked: list[int] = []
for _ in range(m):
k = krum_index([updates[i] for i in left], f)
picked.append(left.pop(k))
return picked
def multi_krum(updates: Sequence[Sequence[float]], f: int, m: int) -> Vector:
"""The mean of the m updates chosen by multi_krum_indices. Same precondition; cost O(m n^2 (d + log n))."""
chosen = multi_krum_indices(updates, f, m)
d = len(updates[0])
return [math.fsum(updates[i][j] for i in chosen) / m for j in range(d)]
def average(updates: Sequence[Sequence[float]]) -> Vector:
"""The plain coordinatewise mean, the rule that one Byzantine update can move anywhere. Cost O(n d)."""
n = len(updates)
return [math.fsum(u[j] for u in updates) / n for j in range(len(updates[0]))]
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_krum_aggregation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/krum-aggregation/. The authors are listed in prov/NQC1A8.jsonl.
"""Tests of Krum on updates built from fixed seeds: brute force over subsets, the distance bound, and a small training run."""
import itertools
import math
import random
import mlkit as m
from krum_aggregation import (
average,
check_sizes,
krum,
krum_index,
krum_scores,
multi_krum,
multi_krum_indices,
squared_distance,
)
def brute_scores(updates: list[list[float]], f: int) -> list[float]:
"""s(i) from the definition: the minimum, over all sets S of n - f - 2 other updates, of the sum over S."""
n = len(updates)
k = n - f - 2
out = []
for i in range(n):
dist = {j: squared_distance(updates[i], updates[j]) for j in range(n) if j != i}
out.append(min(math.fsum(dist[j] for j in s) for s in itertools.combinations(sorted(dist), k)))
return out
def brute_index(updates: list[list[float]], f: int) -> int:
s = brute_scores(updates, f)
return min(range(len(s)), key=lambda i: (s[i], i))
def random_instance(rng: random.Random) -> tuple[list[list[float]], int]:
f = rng.randint(0, 2)
n = rng.randint(2 * f + 3, 8)
d = rng.randint(1, 4)
if rng.random() < 0.5:
# small integers, so that equal scores (ties) are common
updates = [[float(rng.randint(-2, 2)) for _ in range(d)] for _ in range(n)]
else:
updates = [[rng.gauss(0.0, 1.0) * rng.choice([1.0, 10.0]) for _ in range(d)] for _ in range(n)]
return updates, f
def test_example_of_the_page() -> None:
v = [[0.0], [1.0], [2.0], [4.0], [10.0]]
assert krum_scores(v, 1) == [5.0, 2.0, 5.0, 13.0, 100.0]
assert krum_index(v, 1) == 1
assert krum(v, 1) == [1.0]
assert average(v) == [3.4]
def test_matches_brute_force_over_subsets() -> None:
rng = random.Random(3101)
for _ in range(600):
updates, f = random_instance(rng)
assert krum_scores(updates, f) == brute_scores(updates, f)
assert krum_index(updates, f) == brute_index(updates, f)
def test_ties_go_to_the_smallest_index() -> None:
v = [[1.0], [0.0], [2.0], [1.0], [1.0]]
# V_0, V_3 and V_4 all have score 0 with f = 1; the first one wins
assert krum_index(v, 1) == 0
assert krum_index([[0.0]] * 5, 1) == 0
def test_rejects_too_few_updates() -> None:
for f in range(0, 4):
for n in range(1, 2 * f + 3):
try:
krum_index([[0.0]] * n, f)
except ValueError:
pass
else:
raise AssertionError((n, f))
try:
check_sizes(n, f)
except ValueError:
pass
else:
raise AssertionError((n, f))
krum_index([[0.0]] * (2 * f + 3), f)
def test_multi_krum_matches_repeated_brute_force() -> None:
rng = random.Random(3102)
for _ in range(300):
updates, f = random_instance(rng)
n = len(updates)
mm = rng.randint(1, n - 2 * f - 2)
left = list(range(n))
expect = []
for _ in range(mm):
k = brute_index([updates[i] for i in left], f)
expect.append(left.pop(k))
assert multi_krum_indices(updates, f, mm) == expect
mean = multi_krum(updates, f, mm)
for j in range(len(updates[0])):
assert abs(mean[j] - sum(updates[i][j] for i in expect) / mm) < 1e-9
assert multi_krum_indices(updates, f, 1) == [krum_index(updates, f)]
def byzantine_updates(rng: random.Random, honest: list[list[float]], b: int, d: int) -> list[list[float]]:
"""Abstract Byzantine strategies on synthetic vectors, chosen at random."""
kind = rng.randrange(4)
center = average(honest)
if kind == 0: # far away
return [[rng.gauss(0.0, 100.0) for _ in range(d)] for _ in range(b)]
if kind == 1: # the collusion of Figure 3: b - 1 far points, one at the barycenter of all
far = [[100.0 + rng.random() for _ in range(d)] for _ in range(b - 1)]
bary = average(honest + far) if far else center
return far + [bary]
if kind == 2: # close to the honest mean, shifted by a random multiple of the honest spread
spread = max(math.sqrt(squared_distance(h, center)) for h in honest)
direction = [rng.gauss(0.0, 1.0) for _ in range(d)]
r = m.norm2(direction) or 1.0
c = rng.uniform(0.0, 3.0) * spread / r
return [m.add(center, m.scale(c, direction)) for _ in range(b)]
# copies of one honest update with a small shift
base = rng.choice(honest)
return [[a + rng.gauss(0.0, 0.5) for a in base] for _ in range(b)]
def test_choice_is_close_to_some_honest_update() -> None:
"""The theorem of the page: min_j ||V* - V_j||^2 <= (n - f - 2) / (n - 2 f - 1) rho^2."""
rng = random.Random(3103)
for _ in range(600):
f = rng.randint(1, 2)
n = rng.randint(2 * f + 3, 9)
d = rng.randint(1, 4)
b = rng.randint(0, f)
honest = [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(n - b)]
updates = honest + byzantine_updates(rng, honest, b, d)
rng.shuffle(updates)
chosen = krum(updates, f)
rho2 = min(max(squared_distance(h, g) for g in honest) for h in honest)
delta2 = min(squared_distance(chosen, h) for h in honest)
assert delta2 <= (n - f - 2) / (n - 2 * f - 1) * rho2 * (1 + 1e-12) + 1e-12
def test_one_byzantine_update_moves_the_average_anywhere() -> None:
"""Lemma 1 of Blanchard et al.: a linear rule is moved to any target U by one update."""
rng = random.Random(3104)
for _ in range(100):
n, d = rng.randint(4, 8), rng.randint(1, 4)
honest = [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(n - 1)]
target = [rng.uniform(-50, 50) for _ in range(d)]
bad = [n * target[j] - math.fsum(h[j] for h in honest) for j in range(d)]
got = average(honest + [bad])
assert all(abs(a - t) < 1e-9 for a, t in zip(got, target))
def test_training_run_with_two_byzantine_clients() -> None:
"""Seeded logistic regression with 9 clients, 2 of them Byzantine, on synthetic blobs."""
rng = random.Random(3105)
n, f, d = 9, 2, 2
centers = [[-1.0, -1.0], [1.0, 1.0]]
clients = [m.make_blobs(rng, 10, d, centers, 0.7) for _ in range(n - f)]
test = m.make_blobs(rng, 200, d, centers, 0.7)
def honest_update(w: list[float], b: float, data: m.Data) -> list[float]:
gw, gb = [0.0] * d, 0.0
for x, y in data:
g, g0 = m.grad_w_logistic(w, b, x, y)
gw = m.add(gw, g)
gb += g0
return [a / len(data) for a in gw] + [gb / len(data)]
def run(rule) -> float:
w, b = [0.0] * d, 0.0
for _ in range(40):
ups = [honest_update(w, b, c) for c in clients]
mean = average(ups)
ups += [m.scale(-10.0, mean) for _ in range(f)]
step = rule(ups)
w = [w[j] - 0.5 * step[j] for j in range(d)]
b -= 0.5 * step[d]
return m.accuracy(lambda x: 1 if m.dot(w, x) + b > 0 else 0, test)
assert run(lambda u: krum(u, f)) >= 0.9
assert run(lambda u: multi_krum(u, f, 3)) >= 0.9
assert run(average) <= 0.5
History
Byzantine faults come from Lamport, Shostak and Pease (1982). Blanchard, El Mhamdi, Guerraoui and Stainer (2017) brought the model to distributed stochastic gradient descent, showed that linear rules break with one Byzantine worker, and proposed Krum with its resilience and convergence analysis. In 2018 Yin et al. analyzed the coordinate-wise median and trimmed mean, and El Mhamdi, Guerraoui and Rouault showed that Krum allows a large drift in high dimension and proposed Bulyan. Baruch, Baruch and Goldberg (2019) showed small coordinated changes that pass these rules.
References
- Peva Blanchard, El Mahdi El Mhamdi, Rachid Guerraoui and Julien Stainer, Machine learning with adversaries, Byzantine tolerant gradient descent, Advances in Neural Information Processing Systems 30 (NeurIPS) 2017, arXiv:1703.02757, arXiv:1703.02757v1: Lemma 1 (Section 3, linear rules), Definition 1 ((alpha, f)-Byzantine resilience), Section 4 (the score, Lemma 2 on the cost and Proposition 1 with eta(n, f)), Section 6 (m-Krum)
- Dong Yin, Yudong Chen, Kannan Ramchandran and Peter Bartlett, Byzantine-robust distributed learning, towards optimal statistical rates, Proceedings of the 35th International Conference on Machine Learning (ICML) 2018, the coordinate-wise median and coordinate-wise trimmed mean rules and their error rates
- El Mahdi El Mhamdi, Rachid Guerraoui and Sebastien Rouault, The hidden vulnerability of distributed learning in Byzantium, Proceedings of the 35th International Conference on Machine Learning (ICML) 2018, attacks on Krum in high dimension and the Bulyan rule, which runs Krum repeatedly and then a coordinate-wise trimmed mean
- Moran Baruch, Gilad Baruch and Yoav Goldberg, A little is enough, circumventing defenses for distributed learning, Advances in Neural Information Processing Systems 32 (NeurIPS) 2019, Byzantine updates that stay within the spread of the honest updates and still bias the model under Krum and the median rules
- Leslie Lamport, Robert Shostak and Marshall Pease, The Byzantine generals problem, ACM Transactions on Programming Languages and Systems 4(3), 1982, pages 382 to 401, the Byzantine fault model, in which faulty processes behave arbitrarily and may collude
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 NQC1A8 Edit this page History Report an error Markdown