Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Peva Blanchard, El Mahdi El Mhamdi, Rachid Guerraoui, Julien Stainer, 2017

Krum is an aggregation rule for distributed training with a parameter server: nn clients each send an update vector Vi∈RdV_i \in \mathbb{R}^d (a gradient estimate), at most ff of them are Byzantine and may send anything, and the server must pick a vector to step with. Krum gives each update the score s(i)s(i), the sum of the squared distances from ViV_i to its n−f−2n - f - 2 nearest other updates, and returns the update with the smallest score. It is defined only when n>2f+2n > 2f + 2. 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 ff of the nn updates in each round, with arbitrary values. The server is trusted, and the honest updates are i.i.d. unbiased estimates of the gradient gg.

Input. Vectors V1,…,Vn∈RdV_1, \ldots, V_n \in \mathbb{R}^d and an integer f≥0f \ge 0 with n>2f+2n > 2f + 2.

Output. One of the input vectors, Vi∗V_{i^*}, where i∗i^* minimizes

s(i)=min⁡S⊆{1..n}∖{i}, ∣S∣=n−f−2 ∑j∈S∥Vi−Vj∥2,s(i) = \min_{S \subseteq \{1..n\} \setminus \{i\},\ |S| = n - f - 2} \ \sum_{j \in S} \lVert V_i - V_j \rVert^2 ,

with ties broken toward the smallest index, as Blanchard et al. do. The sum of the n−f−2n - f - 2 smallest of the distances from ViV_i is this minimum.

Why n−f−2n - f - 2. Each update has n−1n - 1 others. Leaving out f+1f + 1 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 n−f−2>fn - f - 2 > f is what n>2f+2n > 2f + 2 says: the neighbor set of any update holds more updates than there are Byzantine ones, so at least n−2f−2≥1n - 2f - 2 \ge 1 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 2f+2<n2f + 2 < n is tight is left open in their Section 7.

The algorithm

  1. KRUM(V_1, ..., V_n, f)
  2. 1if n <= 2f + 2 then fail
  3. 2for i = 1 to n do
  4. 3D <- [ ||V_i - V_j||^2 for every j != i ]
  5. 4sort D in increasing order
  6. 5s(i) <- D[1] + ... + D[n - f - 2]
  7. 6if s(i) < best score so far then i* <- i
  8. 7return V_{i*}

Line L1 rejects inputs where the guarantee cannot hold. Lines L3 to L5 compute the score: the n−1n - 1 squared distances, sorted, and the sum of the first n−f−2n - f - 2. 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 mm updates by running Krum, removing the winner and running again, and averages the mm winners. Each round must be valid, so n−m+1>2f+2n - m + 1 > 2f + 2; the paper states the condition as 2f+2<n−m2f + 2 < n - m.

Example

One coordinate, n=5n = 5, f=1f = 1, so each score sums the n−f−2=2n - f - 2 = 2 smallest squared distances. The updates are V=(0,1,2,4,10)V = (0, 1, 2, 4, 10), and V5=10V_5 = 10 is Byzantine.

ii ViV_i squared distances to the others two smallest s(i)s(i)
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 V2=1V_2 = 1. The average is 17/5=3.417/5 = 3.4, already pulled toward the Byzantine value; with V5=1000V_5 = 1000 the average would be 201.4201.4, and Krum would still return 11.

Now let the Byzantine client send 1.51.5 instead. Its squared distances are 2.25,0.25,0.25,6.252.25, 0.25, 0.25, 6.25, so its score is 0.50.5, and the score of V2V_2 becomes 1+0.25=1.251 + 0.25 = 1.25. Krum picks the Byzantine vector. But it lies between two honest updates, and the bound of the next section caps the harm: here ρ2=4\rho^2 = 4 (the honest update 22 is within squared distance 44 of every honest update), and the chosen vector must be within squared distance n−f−2n−2f−1ρ2=22⋅4=4\frac{n - f - 2}{n - 2f - 1} \rho^2 = \frac{2}{2} \cdot 4 = 4 of some honest update. It is within 0.250.25.

Correctness

The computation. The sum of the n−f−2n - f - 2 smallest entries of DD is the minimum over all sets SS of that size, so line L5 computes s(i)s(i) exactly and line L6 returns the first minimizer.

Theorem (a deterministic bound, proved on this page). Let HH be the set of honest indices, with at most ff Byzantine indices and n>2f+2n > 2f + 2, and let ρ2=min⁡i∈Hmax⁡j∈H∥Vi−Vj∥2\rho^2 = \min_{i \in H} \max_{j \in H} \lVert V_i - V_j \rVert^2. Then

min⁡j∈H∥Vi∗−Vj∥2 ≤ n−f−2n−2f−1 ρ2.\min_{j \in H} \lVert V_{i^*} - V_j \rVert^2 \ \le\ \frac{n - f - 2}{n - 2f - 1}\, \rho^2 .

The idea, from the proof of Proposition 1 of Blanchard et al.: an honest ii has at least n−f−1n - f - 1 honest others, so s(i)≤(n−f−2)ρi2s(i) \le (n - f - 2) \rho_i^2; a Byzantine i∗i^* has at most f−1f - 1 Byzantine others, so at least n−2f−1n - 2f - 1 of its n−f−2n - f - 2 nearest are honest, and s(i∗)≥(n−2f−1)min⁡j∈H∥Vi∗−Vj∥2s(i^*) \ge (n - 2f - 1) \min_{j \in H} \lVert V_{i^*} - V_j \rVert^2. Combine with s(i∗)≤s(i)s(i^*) \le s(i). 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 gg and E∥G−g∥2=dσ2\mathbb{E}\lVert G - g \rVert^2 = d \sigma^2, 2f+2<n2f + 2 < n and η(n,f)d σ<∥g∥\eta(n, f) \sqrt{d}\, \sigma < \lVert g \rVert, then Krum is (α,f)(\alpha, f)-Byzantine resilient with sin⁡α=η(n,f)d σ/∥g∥\sin \alpha = \eta(n, f) \sqrt{d}\, \sigma / \lVert g \rVert: ⟨E Kr,g⟩≥(1−sin⁡α)∥g∥2>0\langle \mathbb{E}\,\mathrm{Kr}, g \rangle \ge (1 - \sin \alpha) \lVert g \rVert^2 > 0, and the moments of order 2 to 4 of the output are bounded by those of GG. Here

η(n,f)=2(n−f+f(n−f−2)+f2(n−f−1)n−2f−2),\eta(n, f) = \sqrt{2 \left(n - f + \frac{f (n - f - 2) + f^2 (n - f - 1)}{n - 2f - 2}\right)},

which is O(n)O(n) when ff grows with nn and O(n)O(\sqrt{n}) when ff is fixed. Their Section 5 turns this into almost sure convergence of the gradient norm to a region where ∥∇Q∥≤ηd σ\lVert \nabla Q \rVert \le \eta \sqrt{d}\, \sigma.

Proof: Krum returns the update of smallest score, and that update is close to an honest onefull

Setting. The input is V1,…,Vn∈RdV_1, \ldots, V_n \in \mathbb{R}^d and an integer f≥0f \ge 0 with n>2f+2n > 2f + 2. Write k=n−f−2k = n - f - 2, so k≥f+1≥1k \ge f + 1 \ge 1. For i≠ji \ne j let dij=∥Vi−Vj∥2d_{ij} = \lVert V_i - V_j \rVert^2. The score is

s(i)=min⁡{∑j∈Sdij : S⊆{1,…,n}∖{i}, ∣S∣=k}.s(i) = \min \Big\{ \sum_{j \in S} d_{ij} \ :\ S \subseteq \{1, \ldots, n\} \setminus \{i\},\ |S| = k \Big\}.

Claim 1 (the computation). Line L5 sets s(i)s(i) to this minimum, and line L7 returns Vi∗V_{i^*} where i∗i^* is the smallest index with s(i∗)=min⁡is(i)s(i^*) = \min_i s(i).

Proof. Line L3 builds the list of the n−1n - 1 values dijd_{ij}, j≠ij \ne i, and line L4 sorts it, so that D[1]≤D[2]≤⋯≤D[n−1]D[1] \le D[2] \le \cdots \le D[n-1]. Let SS be any set of kk indices other than ii, and list its values in increasing order as e1≤⋯≤eke_1 \le \cdots \le e_k. For each t≤kt \le k, at least tt entries of DD are at most ete_t (the values e1,…,ete_1, \ldots, e_t themselves), so D[t]≤etD[t] \le e_t. Summing over tt gives D[1]+⋯+D[k]≤∑j∈SdijD[1] + \cdots + D[k] \le \sum_{j \in S} d_{ij}. The first kk entries of DD are themselves the values of one such set SS. So line L5 computes the minimum s(i)s(i). 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 n≤2f+2n \le 2f + 2, so no other input reaches lines L2 to L7. □\square

Claim 2 (closeness to an honest update). Let H⊆{1,…,n}H \subseteq \{1, \ldots, n\} be a set of honest indices whose complement BB has ∣B∣≤f|B| \le f. Let

ρ2=min⁡i∈Hmax⁡j∈Hdij,with dii=0.\rho^2 = \min_{i \in H} \max_{j \in H} d_{ij}, \qquad \text{with } d_{ii} = 0 .

Then the index i∗i^* returned by Krum satisfies

min⁡j∈H∥Vi∗−Vj∥2 ≤ n−f−2n−2f−1 ρ2.\min_{j \in H} \lVert V_{i^*} - V_j \rVert^2 \ \le\ \frac{n - f - 2}{n - 2f - 1}\, \rho^2 .

Proof. If i∗∈Hi^* \in H, the left side is 00 and there is nothing to prove. So let i∗∈Bi^* \in B, and let c∈Hc \in H be an index that attains ρ2\rho^2, so that dcj≤ρ2d_{cj} \le \rho^2 for every j∈Hj \in H.

Upper bound on s(c)s(c). The honest indices other than cc number ∣H∣−1≥n−f−1≥k|H| - 1 \ge n - f - 1 \ge k. Take any kk of them as the set SS in the definition of s(c)s(c). Each term is at most ρ2\rho^2, so s(c)≤kρ2=(n−f−2)ρ2s(c) \le k \rho^2 = (n - f - 2) \rho^2.

Lower bound on s(i∗)s(i^*). Let S∗S^* be a set of kk indices other than i∗i^* that attains s(i∗)s(i^*). The Byzantine indices other than i∗i^* number ∣B∣−1≤f−1|B| - 1 \le f - 1, so S∗S^* holds at least k−(f−1)=n−2f−1k - (f - 1) = n - 2f - 1 honest indices. This count is positive because n>2f+2n > 2f + 2. Let δ2=min⁡j∈Hdi∗j\delta^2 = \min_{j \in H} d_{i^* j}. Each honest j∈S∗j \in S^* has di∗j≥δ2d_{i^* j} \ge \delta^2, and every term is nonnegative, so s(i∗)≥(n−2f−1)δ2s(i^*) \ge (n - 2f - 1) \delta^2.

Combination. By Claim 1, s(i∗)≤s(c)s(i^*) \le s(c). Hence (n−2f−1)δ2≤(n−f−2)ρ2(n - 2f - 1) \delta^2 \le (n - f - 2) \rho^2, and dividing by the positive number n−2f−1n - 2f - 1 gives the claim. □\square

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 n−2f−1n - 2f - 1 that holds for a Byzantine winner in place of their count n−2f−2n - 2f - 2, which holds for any index. The argument of Claim 2 uses only n−2f−1≥1n - 2f - 1 \ge 1, that is n≥2f+2n \ge 2f + 2; Krum itself, as defined by Blanchard et al. and in line L1, requires n>2f+2n > 2f + 2. The constant ρ2\rho^2 grows with the spread of the honest updates, which in dimension dd with per-coordinate noise σ\sigma is of order dσ2d \sigma^2; 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. ■\blacksquare

Complexity

  • Time. Each of the nn updates needs n−1n - 1 distances at O(d)O(d) each (line L3) and a sort of n−1n - 1 numbers (line L4), so the total is O(n2(d+log⁡n))O(n^2 (d + \log n)), Lemma 2 of Blanchard et al. A selection algorithm such as quickselect in place of the sort gives O(n2d)O(n^2 d) expected time. Computing each distance once and storing the matrix halves the distance work and costs O(n2)O(n^2) space.
  • Space. O(n)O(n) extra for the list DD of one row, beyond the input.
  • m-Krum. mm runs of Krum, so O(mn2(d+log⁡n))O(m n^2 (d + \log n)).

Properties

  • Output is an input. Krum returns one of the ViV_i 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 ∑iλiVi\sum_i \lambda_i V_i with nonzero λi\lambda_i can be moved to any vector UU by one Byzantine update Vn=1λnU−∑i<nλiλnViV_n = \frac{1}{\lambda_n} U - \sum_{i < n} \frac{\lambda_i}{\lambda_n} V_i. 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 f<(n−2)/2f < (n - 2)/2 Byzantine updates, close to the bound f<n/2f < n/2 of the median.

Variants and improvements

  • m-Krum (Blanchard et al., Section 6). Average mm winners of repeated Krum. The paper also mentions taking the mm 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 O(nd)O(n d) expected for the median by selection.
  • Bulyan (El Mhamdi et al. 2018). Select θ=n−2f\theta = n - 2f updates by repeated Krum, then take a coordinate-wise trimmed mean around the median; it needs n≥4f+3n \ge 4f + 3 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 nn is small enough that n2n^2 distance computations per round are cheap. Prefer the coordinate-wise median or trimmed mean when dd is large and nn is large, since they cost O(nd)O(n d). 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 ∥Vi−Vj∥2\lVert V_i - V_j \rVert^2. 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 n−f−2n - f - 2 distances to other updates. Sorting all nn distances, including the zero distance to itself, and then summing n−f−2n - f - 2 values sums one other too few. Lemma 2 of Blanchard et al. sums n−f−1n - f - 1 values for this reason, since that list includes the zero.
  • Skipping the size check. Line L1 must reject n≤2f+2n \le 2f + 2, the range where the theorem of Blanchard et al. does not apply. For n≤2f+1n \le 2f + 1 the rule fails outright: then n−f−2≤f−1n - f - 2 \le f - 1, so ff colluders that send the same vector have only each other among their nearest, get score 00 and win.
  • Ignoring attacks inside the spread. The bound limits the distance to the honest updates in terms of their spread ρ\rho. 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 ρ\rho grows like d σ\sqrt{d}\, \sigma, 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 n−f−2n - f - 2 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.

krum_aggregation.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example