Simple Algorithm
Artificial Intelligence · Deep Layer · 24 min

Federated Learning

Training without centralizing data.

Your phone's keyboard can learn from what you type without your words leaving the device: the model travels to the data, and only updates travel back. That changes the optimization problem, because clients hold different data and communicate rarely, and the threat model, because updates can leak the data they came from. This lesson analyzes FedAvg and client drift, the cryptography of secure aggregation, and the attacks that make federated learning private only in combination with other tools.

What you’ll learn

  • Formulate federated optimization, implement FedAvg, and explain when local steps save communication.
  • Derive client drift on heterogeneous quadratics, and show how SCAFFOLD's control variates remove it.
  • Explain secure aggregation by pairwise masking, its recovery from dropouts, and what it does and does not hide.
  • Reconstruct inputs from gradients (exactly for a linear layer, by optimization in general), and combine federated learning with user-level differential privacy.

Federated optimization

Federated learning minimizes a weighted average of client objectives without collecting the data:

min⁡w F(w)=∑k=1Kpk Fk(w),Fk(w)=Eξ∼Dk ℓ(w;ξ),pk=nkn.\min_{\mathbf w}\ F(\mathbf w)=\sum_{k=1}^Kp_k\,F_k(\mathbf w),\qquad F_k(\mathbf w)=\E_{\xi\sim\data_k}\,\ell(\mathbf w;\xi),\qquad p_k=\frac{n_k}{n}.

The setting differs from datacenter training in four ways (Kairouz et al., 2021). Data are non-IID, since each Dk\data_k reflects one user, and unbalanced. Clients are many (up to millions of phones), and only a small, changing fraction takes part in each round. Communication, especially upload, is slow and costly relative to computation. Cross-device deployments involve phones; cross-silo ones a few reliable, data-rich institutions such as hospitals.

text
FEDAVG (McMahan et al., 2017)
server:  w ← w₀
         for round t = 1 … T:
             S ← random set of m clients (a fraction of all K)
             send w to every k ∈ S;  receive w_k
             Δ ← Σ_{k∈S} (n_k / n_S) · (w − w_k)        # averaged local progress
             w ← w − η_g · Δ                            # η_g = 1 is plain averaging
client k: y ← w
          for E local epochs, for each mini-batch b of the local data:
              y ← y − η · ∇ℓ(y; b)
          return y

With ηg=1\eta_g=1 the server simply averages the client models. Treating Δ\Delta as a pseudo-gradient and applying momentum or Adam on the server gives the adaptive federated optimizers of Reddi et al. (2021).

Local steps buy communication. With IID data, local SGD reaches a given accuracy with far fewer rounds than synchronizing after every step, with convergence rates matching minibatch SGD under suitable step sizes (Stich, 2019), and McMahan et al. reported 10 to 100 times fewer rounds than one-step-per-round training on their benchmarks. Heterogeneity changes the picture: Woodworth, Patel & Srebro (2020) showed that with differing client objectives, local SGD can do worse than minibatch SGD with the same communication.

Think first If every client ran local SGD to convergence before each average (E→∞E\to\infty), what would FedAvg compute?

Each client would return its own minimizer, so FedAvg would converge to the weighted average of the client optima. That is generally not the minimizer of the average objective: averaging minimizers ignores how sharply each client's loss curves around its minimum. The next step makes this exact.

Heterogeneity and client drift

DerivationClient drift on quadratics
  1. w∗=∑khkak∑khkw^*=\frac{\sum_kh_ka_k}{\sum_kh_k}

    Take KK equally weighted clients with fk(w)=hk2(w−ak)2f_k(w)=\frac{h_k}{2}(w-a_k)^2. The global objective F=1K∑kfkF=\frac1K\sum_kf_k is minimized at the curvature-weighted mean:

  2. wk=ak+ρk (w−ak),ρk=(1−ηhk)Ew_k=a_k+\rho_k\,(w-a_k),\qquad\rho_k=(1-\eta h_k)^E

    EE local gradient steps with rate η\eta (where 0<ηhk<20<\eta h_k<2) shrink the distance to aka_k by 1−ηhk1-\eta h_k each time:

  3. w+=1K∑k[ak+ρk(w−ak)]⟹wˉ=∑k(1−ρk) ak∑k(1−ρk)w^+=\frac1K\sum_k\big[a_k+\rho_k(w-a_k)\big]\quad\Longrightarrow\quad\bar w=\frac{\sum_k(1-\rho_k)\,a_k}{\sum_k(1-\rho_k)}

    The server's average is a contraction in ww, with a unique fixed point:

  4. With E=1E=1, 1−ρk=ηhk1-\rho_k=\eta h_k and wˉ=w∗\bar w=w^*: one local step is plain gradient descent. As E→∞E\to\infty, ρk→0\rho_k\to0 and wˉ=1K∑kak\bar w=\frac1K\sum_ka_k, the unweighted average of client optima. In between, FedAvg converges to the wrong point whenever curvatures differ: client drift.

Predict before you look

Two clients have h=(1,3)h=(1,3) and a=(0,1)a=(0,1), so w∗=0.75w^*=0.75. FedAvg uses η=0.1\eta=0.1 and E=10E=10 local steps. Where does it converge?

Show the answer

0.6

ρ1=0.910≈0.349\rho_1=0.9^{10}\approx0.349 and ρ2=0.710≈0.028\rho_2=0.7^{10}\approx0.028, so the weights 1−ρk1-\rho_k are 0.651 and 0.972, and wˉ=0.972/(0.651+0.972)≈0.60\bar w=0.972/(0.651+0.972)\approx0.60. The flat client pulls the answer toward its optimum far more than its curvature deserves; with E→∞E\to\infty the limit would be 0.5.

Three remedies. Decaying learning rates make FedAvg converge to the true optimum, at rates such as O(1/T)\order{1/T} for smooth, strongly convex objectives, with constants that grow with heterogeneity (X. Li et al., 2020). FedProx (T. Li et al., 2020) adds μ2∥w−wt∥2\frac\mu2\norm{\mathbf w-\mathbf w_t}^2 to each local objective, limiting how far a client can wander from the server model. SCAFFOLD (Karimireddy et al., 2020) corrects every local step with control variates, c≈∇F\mathbf c\approx\nabla F kept by the server and ck≈∇Fk\mathbf c_k\approx\nabla F_k kept by client kk, using the update y←y−η(∇Fk(y)−ck+c)\mathbf y\leftarrow\mathbf y-\eta\big(\nabla F_k(\mathbf y)-\mathbf c_k+\mathbf c\big); its convergence guarantees do not depend on how different the clients are.

DerivationSCAFFOLD removes the drift on the quadratics
  1. y←y−η(hk(y−ak)−hk(w−ak)+F′(w))=y−η(hk(y−w)+F′(w))y\leftarrow y-\eta\big(h_k(y-a_k)-h_k(w-a_k)+F'(w)\big)=y-\eta\big(h_k(y-w)+F'(w)\big)

    Use exact control variates evaluated at the round's starting point ww, namely ck=hk(w−ak)c_k=h_k(w-a_k) and c=F′(w)c=F'(w). The local step becomes

  2. dE=−ηF′(w)∑j=0E−1(1−ηhk)j=−F′(w) 1−ρkhkd_E=-\eta F'(w)\sum_{j=0}^{E-1}(1-\eta h_k)^j=-F'(w)\,\frac{1-\rho_k}{h_k}

    With d=y−wd=y-w, starting from d0=0d_0=0, the recursion is d←(1−ηhk)d−ηF′(w)d\leftarrow(1-\eta h_k)d-\eta F'(w), a geometric sum:

  3. w+=w−F′(w)⋅1K∑k1−ρkhkw^+=w-F'(w)\cdot\frac1K\sum_k\frac{1-\rho_k}{h_k}

    The server's average is a gradient step on the global objective, with an effective step size; its fixed point is F′(w)=0F'(w)=0, the true optimum w∗w^*, for any EE. □\square

Secure aggregation

The server needs only the sum of the clients' update vectors xk\mathbf x_k. Secure aggregation (Bonawitz et al., 2017) lets it learn ∑kxk\sum_k\mathbf x_k and nothing else about any single xk\mathbf x_k, even when clients drop out partway through, using only cheap cryptography: key agreement, a pseudorandom generator (PRG) and secret sharing.

DerivationPairwise masks cancel
  1. yu=xu+∑v>uPRG(suv)−∑v<uPRG(svu)(modR)\mathbf y_u=\mathbf x_u+\sum_{v>u}\mathrm{PRG}(s_{uv})-\sum_{v<u}\mathrm{PRG}(s_{vu})\pmod R

    Every pair of clients u<vu<v agrees on a seed suvs_{uv} by Diffie–Hellman key agreement; the server relays the public keys but cannot compute the seeds. Client uu sends its update hidden under pseudorandom masks, with all arithmetic modulo RR:

  2. ∑uyu=∑uxu+∑u<vPRG(suv)−∑u<vPRG(suv)=∑uxu(modR)\sum_u\mathbf y_u=\sum_u\mathbf x_u+\sum_{u<v}\mathrm{PRG}(s_{uv})-\sum_{u<v}\mathrm{PRG}(s_{uv})=\sum_u\mathbf x_u\pmod R

    Summing over clients, each pair's mask appears once with each sign:

  3. Each yu\mathbf y_u on its own is masked by PRG outputs the server cannot predict, so it looks uniformly random: it reveals nothing about xu\mathbf x_u to a computationally bounded server.

Dropouts. If client vv vanishes after the others have masked with suvs_{uv}, unmatched masks remain in the sum. So each client splits its Diffie–Hellman secret into tt-of-nn Shamir shares held by the others; the survivors reveal the shares belonging to dropped clients, and the server removes their masks. A lying server could then claim that a live client had dropped and unmask its yu\mathbf y_u. To prevent this, each client adds a second, self-generated mask PRG(bu)\mathrm{PRG}(b_u), also secret-shared, and for each client the honest parties reveal shares of either bub_u (if it survived) or its key (if it dropped), never both.

Cost and limits. For a thousand clients with million-entry vectors the protocol cost less than twice the communication of sending the updates in the clear, though the original server computation grows quadratically with the number of clients; later versions talk to only a logarithmic number of neighbors (Bell et al., 2020). Secure aggregation does not hide the sum itself, which can expose a client through differencing across rounds with different participants. It does not stop malicious clients from poisoning the model, and it is in tension with robust aggregation rules (coordinate-wise median, trimmed mean, Krum), which need to inspect individual updates.

Check your understanding

Which statement about secure aggregation is correct?

  1. It makes the trained model differentially private
  2. It protects the model against poisoned updates from malicious clients
  3. The server learns the sum of the participating clients' updates and nothing else about any individual update
  4. It hides even the sum of the updates from the server
Show the answer

C. The server learns the sum of the participating clients' updates and nothing else about any individual update

Pairwise masks cancel only in the sum, and secret sharing handles dropouts. Everything the sum itself reveals is still revealed, which is why secure aggregation is combined with differential privacy.

What updates leak, and user-level privacy

DerivationA linear layer hands over its input
  1. ∂L∂W=∂L∂z x⊤,∂L∂b=∂L∂z\frac{\partial\loss}{\partial W}=\frac{\partial\loss}{\partial\mathbf z}\,\mathbf x^\top,\qquad\frac{\partial\loss}{\partial\mathbf b}=\frac{\partial\loss}{\partial\mathbf z}

    For a fully connected layer z=Wx+b\mathbf z=W\mathbf x+\mathbf b applied to one example, the chain rule gives the weight and bias gradients:

  2. x⊤=∂L/∂Wi,:∂L/∂biwhenever ∂L∂bi≠0\mathbf x^\top=\frac{\partial\loss/\partial W_{i,:}}{\partial\loss/\partial b_i}\qquad\text{whenever }\frac{\partial\loss}{\partial b_i}\neq0

    Row ii of the weight gradient is the input scaled by the ii-th bias gradient, so any row with a nonzero bias gradient returns the input exactly:

  3. For a batch, both gradients are averages over examples, and the same ratio returns a weighted combination of the batch's inputs, with weights that vary from row to row. Recovery is exact for a single example; larger batches and several local steps blur the leak without removing it.

For general architectures, attacks optimize. Deep leakage from gradients (Zhu, Liu & Han, 2019) fits dummy inputs and labels by gradient descent so that their gradient matches the shared one, min⁡x′,y′∥∇wℓ(w;x′,y′)−∇wℓ(w;x,y)∥2\min_{\mathbf x',y'}\norm{\nabla_{\mathbf w}\ell(\mathbf w;\mathbf x',y')-\nabla_{\mathbf w}\ell(\mathbf w;\mathbf x,y)}^2, and recovered images pixel by pixel and text token by token for small batches; the label can be read off the signs of the last layer's gradient (Zhao, Mopuri & Bilen, 2020). Geiping et al. (2020), matching gradient directions under an image prior, recovered recognizable ImageNet-sized images from trained networks, even from updates averaged over several local steps. Larger batches and more local steps help only partly, and compressing or sparsifying updates helps little; secure aggregation hides individual updates from the server, and differential privacy bounds what any observer can learn.

User-level differential privacy. DP-FedAvg (McMahan, Ramage, Talwar & Zhang, 2018) samples clients with probability qq per round, clips each client's entire update to norm SS, and adds N(0,σ2S2I)\mathcal N(0,\sigma^2S^2I) to the sum. The unit of privacy is a user's whole dataset, however many examples it holds, and the accounting is DP-SGD's with clients in the role of examples. Because the noise is divided among the mm clients of a round (per-coordinate noise about σS/m\sigma S/m in the average), thousands of clients per round are needed for good accuracy. With secure aggregation each client can add a share of the noise (the distributed discrete Gaussian; Kairouz, Liu & Steinke, 2021), so no party ever sees an un-noised sum. Gboard's production language models have been trained with federated learning under formal user-level DP guarantees (Xu et al., 2023).

Key takeaways

  • Federated optimization minimizes ∑kpkFk\sum_kp_kF_k with non-IID, unbalanced clients, partial participation and costly communication; FedAvg trades communication rounds for local computation.
  • On heterogeneous quadratics FedAvg converges to ∑k(1−ρk)ak/∑k(1−ρk)\sum_k(1-\rho_k)a_k/\sum_k(1-\rho_k), the optimum only for E=1E=1; SCAFFOLD's control variates turn each round into a global gradient step and remove the drift.
  • Secure aggregation reveals only the sum: pairwise masks cancel, Shamir shares repair dropouts and self-masks stop a lying server; it prevents neither poisoning nor leakage from the sum itself.
  • Gradients leak: one example's input can be read exactly off a linear layer's gradient, and optimization attacks reconstruct images and text from small batches.
  • User-level differential privacy (clip whole client updates, add Gaussian noise, account as in DP-SGD) is what makes federated training formally private, and it needs many clients per round.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does FedAvg with many local epochs on non-IID data converge to the wrong point, even with exact gradients?

  1. Because clients are sampled at random
  2. Because each client drifts toward its own optimum, and an average of client optima differs from the minimizer of the average objective when curvatures differ
  3. Because the learning rate is too small
  4. Because averaging weights is a nonlinear operation
Show the answer

B. Because each client drifts toward its own optimum, and an average of client optima differs from the minimizer of the average objective when curvatures differ

On quadratics the fixed point weights each client's optimum by 1−ρk1-\rho_k instead of by its curvature hkh_k; only E=1E=1 (or a decaying step size, or a correction such as SCAFFOLD's) recovers w∗w^*.

Question 2

Three clients use pairwise masks: client 1 sends x1+m12+m13\mathbf x_1+\mathbf m_{12}+\mathbf m_{13}, client 2 sends x2+m23−m12\mathbf x_2+\mathbf m_{23}-\mathbf m_{12}, and client 3 sends x3−m13−m23\mathbf x_3-\mathbf m_{13}-\mathbf m_{23}. What does the server obtain by adding the three messages?

  1. x1+x2+x3+2m12\mathbf x_1+\mathbf x_2+\mathbf x_3+2\mathbf m_{12}
  2. Nothing useful until the clients reveal their masks
  3. x1+x2+x3\mathbf x_1+\mathbf x_2+\mathbf x_3
  4. x2\mathbf x_2 alone
Show the answer

C. x1+x2+x3\mathbf x_1+\mathbf x_2+\mathbf x_3

Each mask is added by one member of its pair and subtracted by the other, so all three cancel. Only the sum survives, and each individual message still looks random.

Question 3

A single example passes through z=Wx+b\mathbf z=W\mathbf x+\mathbf b. An eavesdropper sees ∂L/∂b1=0.5\partial\loss/\partial b_1=0.5 and ∂L/∂W1,:=(0.1, 0.4, 0)\partial\loss/\partial W_{1,:}=(0.1,\ 0.4,\ 0). What was x\mathbf x?

  1. (0.05, 0.2, 0)(0.05,\ 0.2,\ 0)
  2. (0.2, 0.8, 0)(0.2,\ 0.8,\ 0)
  3. (0.1, 0.4, 0)(0.1,\ 0.4,\ 0)
  4. It cannot be determined from gradients
Show the answer

B. (0.2, 0.8, 0)(0.2,\ 0.8,\ 0)

∂L/∂W1,:=(∂L/∂b1) x⊤\partial\loss/\partial W_{1,:}=(\partial\loss/\partial b_1)\,\mathbf x^\top, so x=(0.1,0.4,0)/0.5=(0.2,0.8,0)\mathbf x=(0.1,0.4,0)/0.5=(0.2,0.8,0), exactly.

Question 4

Why does DP-FedAvg clip each client's entire model update, rather than each training example's gradient?

  1. To bound the influence of a whole user, however many examples they hold, which gives user-level privacy
  2. Because per-example gradients cannot be computed on phones
  3. To reduce communication cost
  4. Because clipping per example would give no privacy at all
Show the answer

A. To bound the influence of a whole user, however many examples they hold, which gives user-level privacy

The unit of privacy is whatever has bounded influence. Clipping the whole update bounds one user's total contribution to the sum, so the Gaussian noise protects everything that user contributed.

Further reading

  • H. B. McMahan, E. Moore, D. Ramage, S. Hampson & B. Agüera y Arcas, "Communication-efficient learning of deep networks from decentralized data," AISTATS (2017).
  • P. Kairouz, H. B. McMahan et al., "Advances and open problems in federated learning," Foundations and Trends in Machine Learning 14 (2021).
  • K. Bonawitz et al., "Practical secure aggregation for privacy-preserving machine learning," ACM CCS (2017).
  • S. P. Karimireddy, S. Kale, M. Mohri, S. Reddi, S. Stich & A. T. Suresh, "SCAFFOLD: Stochastic controlled averaging for federated learning," ICML (2020).
  • L. Zhu, Z. Liu & S. Han, "Deep leakage from gradients," NeurIPS (2019).