Phones hold the data and uploads are slow. FedAvg lets each phone train for many steps before the server averages. On MNIST it cut 626 rounds to 18.
Learn how a server trains one model from thousands of devices that never share their data, and why more work on each device means far fewer trips over the network.
Pick how much work each client does per round, then press Run the race. Watch FedAvg and the one-step baseline spend their rounds. Switch to non-IID data and see where the trick weakens. Then we build every piece from zero: the problem, the baseline, the averaging step, why it works, and the evidence.
You need the idea of gradient descent (nudge the weights downhill on a loss) and a little Python for the code. We build the rest from zero.
Paper: H. Brendan McMahan, Eider Moore, Daniel Ramage, Seth Hampson and Blaise Agüera y Arcas (Google), “Communication-Efficient Learning of Deep Networks from Decentralized Data”, AISTATS 2017, arXiv 1602.05629. It is the federated-averaging reference in Rohan Anil’s Hitchhiker’s Guide to Training on Compute Islands (Core Automation, 2 November 2026). Background lesson: Local SGD and model averaging. Every idea is re-taught here in our own words and devices.
Rounds are the paper’s Table 2 (MNIST CNN, 100 clients, C = 0.1, rounds to 99% test accuracy). The four buttons are E = 1 with B = 50, E = 5 with B = 50, E = 5 with B = 10, and E = 20 with B = 10. The bars grow at one shared pace, which is illustrative: the paper reports only the round counts, not this animation.
Chapter 0
Meet the setting where the data stays put, the upload is slow, and every trip to the server must count
Your phone keyboard suggests the next word as you type. To suggest well, it needs a model trained on how people really write: short, messy, full of names and slang. The best training text sits on millions of phones. It holds passwords, messages and addresses. Nobody wants it copied to a data center.
So the phones keep the text. The model comes to the phones instead. A server sends the model out, each phone improves it a little using its own text, and the phones send back only the improvement. This is federated learning: many devices train one shared model while their raw data never leaves them. The 2016 paper by McMahan and colleagues at Google gave it that name and a practical method.
A model is a program made of numbers. Those numbers are its weights (also called parameters), and we write all of them as one long list, w. Training means nudging w until the model makes fewer mistakes. The loss is one number that scores the mistakes: lower is better.
Gradient descent does the nudging. For the current weights, you compute the gradient, which says which way each weight should move to cut the loss fastest. Then you take a small step the other way. The step size is the learning rate, written η. Repeat many times and the loss falls, like a ball rolling downhill.
Real data sets are huge, so each step looks at a small random batch. That is stochastic gradient descent (SGD). The batch is a minibatch, and its size is B. One full pass over all the data is an epoch. If any of this feels new, the optimization lesson builds it slowly. You need only these four ideas here: weights, loss, gradient step, minibatch.
In a data center, the machines sit a few meters apart on very fast links. Computing the gradient takes longer than sending it. On phones the balance flips. The paper says upload bandwidth is typically 1 MB/s or less. Bandwidth is how many bytes the link carries each second, and 1 MB/s means one million bytes per second. Phones also join only when they are charging and on unmetered wi-fi, and each joins a few times a day.
Meanwhile a phone is fast. Its own data set is small, so a few passes over it take little time. The paper's own summary: computation becomes “essentially free” next to communication. So the cost to count is the communication round: the server sends the model out, clients work, clients send results back, and the server combines them.
If every round is that expensive, the goal changes. We do not ask for the fewest computations. We ask for the fewest rounds. The paper's idea is to spend the free resource, computation, to save the scarce one, communication: let each client do a lot of work before it uploads.
Try the cost yourself. Pick a model from the paper and a link speed. Each upload is the whole weight list, and we assume 4 bytes per weight.
Pick one of the paper’s models, then drag the link speed. Each bar is the time a run spends on uploads, one upload per round. The pink bar is the one-step baseline. The warm bar is FedAvg.
Parameter counts and round counts are the paper’s (Tables 2 and 4, and the large-scale LSTM text). The 4 bytes per weight (32-bit numbers) and the one-upload-per-round time are illustrative: they ignore the download, the compute, and the fact that each client joins only some rounds. Targets: 97% (2NN), 99% (CNN), 54% (char LSTM), 10.5% (word LSTM).
Look at the CNN at 1 MB/s. The baseline needs 626 rounds, and the model weighs about 6.7 MB, so uploads alone take roughly 69 minutes. FedAvg needs 18 rounds, or about 2 minutes. Slow the link to 0.25 MB/s and the baseline needs more than four and a half hours. The ratio never changes, but the gap in minutes grows with every slower link.
Rohan Anil's post on training across compute islands lists federated averaging as one of four old ideas behind today's low-communication methods. His words: “Local SGD and federated averaging take many steps between exchanges.” A cluster of GPUs linked by a slow wide-area connection has the same problem as a phone: the link is the scarce resource. The post is the reason this paper is here, and the Local SGD lesson teaches the shared background.
Chapter 1
Write the problem as one formula, then see four ways it differs from training in a data center
Imagine a class of 100 students, and a teacher who wants the whole class to learn a single handwriting-recognition model. Each student has a stack of 600 labelled digit cards. The cards must stay with the students. The teacher can send a model to each student and get a model back. How should the teacher run the lesson?
That is the paper's MNIST setup. The students are clients: phones, in the real setting. The teacher is the server, which holds the shared model and combines what the clients send. The cards are each client's local data set. The paper calls the whole job federated optimization: minimize one loss when the data is spread over many clients and cannot be gathered.
Start with ordinary training. There are n examples in total. For example i, the loss fi(w) says how badly the weights w predict that example. We want the weights that make the average loss small.
Now split the examples over K clients. Client k holds the index set Pk, with nk examples. Its own average loss is Fk(w). The global loss is a weighted average of the client losses, and the weight is each client's share of the data.
A worked case with three clients. Client A holds 600 examples and has loss 0.2 at the current weights. Client B holds 300 and has 0.5. Client C holds 100 and has 0.9. Then n = 1000, and:
f(w) = 0.6 × 0.2 + 0.3 × 0.5 + 0.1 × 0.9 = 0.12 + 0.15 + 0.09 = 0.36
A plain average of the three losses would give 0.533. That is wrong, because it lets the 100-example client count as much as the 600-example one. The share nk / n fixes this, and you will see it again in the averaging step.
If the examples were dealt to the clients at random, each Fk would be a fair, noisy copy of f. Statisticians call such data IID: independent and identically distributed, meaning every client sees the same mix. Most distributed training theory assumes this. The paper lists four properties that break it:
The paper stresses the first, second and fourth. We feel the first one now.
Each small chart is one client. Bars left to right are the digits 0 to 9, and the dashed line is the 10% every client would hold if the world were IID. Switch the split, then press Deal again.
The two splits are the paper’s MNIST partitions: IID is 100 clients of 600 examples after a shuffle; non-IID sorts by label, cuts 200 shards of 300 and gives each client 2 shards. We model MNIST as exactly 6,000 examples per digit (the real counts differ a little). The shuffle uses a fixed seed per deal. Distance = half the sum of |client share − 10%| over the ten digits.
Under the IID split every client's bars sit close to the dashed line, and the distance from the world is tiny. Under the non-IID split a client has two tall bars and eight empty slots. Its local loss Fk describes a two-digit world. A model trained only on it would never learn to say “7” if that client holds only 3s and 5s.
The paper works in synchronous rounds. There is a fixed set of K clients. At the start of each round the server picks a random fraction C of them and sends each the current global weights. Each chosen client computes on its own data and sends an update back. The server applies the updates, and the next round starts. It picks only a fraction because the paper finds diminishing returns from adding more clients past a point.
Here is the data flow for the MNIST CNN, with the shapes written out. A client holds images of shape [600, 28, 28, 1] and labels of shape [600]. The server sends down a weight vector of shape [1,663,370]. The client sends back one of the same shape. No image and no label ever travels. The paper also notes that the update holds no more information than the raw data and usually much less.
Chapter 2
Build the baseline, and see that averaging gradients and averaging models give the same answer
The teacher in our classroom wants the simplest possible lesson. Send the current model to every student. Each student checks the model against their own cards and reports which way to nudge the weights. The teacher combines the nudges and takes one step. Then the class does it all again.
The paper calls this FedSGD, federated SGD. It is the natural first attempt, and it is the baseline in every table. It is also exactly what a data center does with large-batch synchronous SGD, which the paper cites (Chen et al.) as the state of the art there. So it is a fair baseline: if FedAvg beats it, the gain comes from the new idea and not from a weak opponent.
Each round, the server picks a fraction C of the clients. Each picked client k computes the gradient gk of its local loss at the current weights wt, using all of its local data. That gradient has one entry per weight, so for the CNN it has shape [1,663,370]. The server then takes a data-weighted average and steps:
Because the weights nk / n add to 1, the weighted average of the client gradients is exactly the gradient of the global loss, ∇f(wt). That is the rule that slopes add: the slope of a sum is the sum of the slopes. So FedSGD with C = 1 is full-batch gradient descent, only computed in pieces. With C below 1, C sets the size of the global batch.
Here is the observation that opens up the whole paper. Let each client take its own step first and report the resulting weights:
The server’s result is the same. Write wt as ∑(nk/n) wt, which is true because the weights add to 1. Then ∑(nk/n)(wt − ηgk) = wt − η∑(nk/n)gk. A small number check, with two clients holding 3 and 1 shares of the data (weights 0.75 and 0.25), wt = 1, η = 0.5, g = 0.4 and −0.8:
gradient route: 1 − 0.5 × (0.75·0.4 + 0.25·(−0.8)) = 1 − 0.5 × 0.1 = 0.95
model route: 0.75 × (1 − 0.2) + 0.25 × (1 + 0.4) = 0.6 + 0.35 = 0.95
Why bother with a second view of the same step? Because the second view has a knob the first does not. If clients may send back models, a client can take more than one step before it reports. That is FedAvg, and it is the next chapter. First, watch the two routes agree on a toy.
Three clients, each with its own best weights (blue dots, bigger dot = more data). The warm dot is the global model. Press Run a round: each client takes one step (purple), and the server averages. The ring is the other route, one gradient step on all the data.
Toy, not from the paper: each client’s loss is a bowl, Fk(w) = ½ ak |w − mk|2, with data shares 600, 300 and 100 and curvatures a = 1, 2 and 0.5. The star is the best weights for the weighted total loss. The gap between the two routes is computed live.
Press the button several times. The warm dot walks toward the star, one step per round, and the ring always sits on it. The gap is zero up to the computer’s rounding. Every round buys exactly one gradient step, and that is the weakness. The CNN needs 626 rounds to reach 99%, and the 2NN needs 1,468 to reach 97%. Each of those is a full trip across a slow network.
python def fedsgd_round(w, clients, C, lr): m = max(int(C * len(clients)), 1) chosen = random.sample(clients, m) n = sum(c.n for c in chosen) g = sum((c.n / n) * c.grad(w) for c in chosen) # each c.grad(w) has the shape of w return w - lr * g
Here is the failure you would see in practice. The symptom: after hundreds of rounds, accuracy is still climbing slowly, and every round costs a full upload. The measurement: the run needs one round per gradient step, so 626 rounds means 626 steps for the CNN. The fix is not a better optimizer on the server. The fix is to let each client take more than one step per round, which is the next chapter. A larger learning rate does not rescue FedSGD either, because the paper already tuned it on a grid.
Chapter 3
Let each client train for several epochs before it reports, and meet the three knobs C, E and B
Back in the classroom, the teacher notices that a round trip is slow but a student's thinking is fast. Why ask for one nudge when each student could work through their whole card stack a few times, and come back with a much better model? Then the teacher would average the students' models, not their nudges. Fewer trips, more progress each trip.
That is FederatedAveraging, FedAvg. Chapter 2 gave the key: the server already averages models. So we let each client run many gradient steps on its own data before it uploads. At one extreme, a single full-batch step, we get FedSGD back. At the other, a client trains to its own best model, and we get one-shot averaging, which the paper notes can be no better than a single client in the worst case.
The amount of work per round is set by three numbers. Learn their names now, because every table in the paper uses them.
A client with nk examples makes nk / B steps per epoch, so it makes uk = E · nk / B steps per round. Averaged over clients, u = E · n / (K · B), the expected local updates per round. Worked example: MNIST has n = 60,000 examples over K = 100 clients, so nk = 600. With E = 5 and B = 10, u = 5 × 600 / 10 = 300. With E = 20 and B = 10, u = 1,200. FedSGD is E = 1 and B = ∞, so u = 1.
The paper’s Algorithm 1 has two halves. The server half runs in the data center. The client half runs on each phone.
python # Server executes w = init_weights() # shape [d], e.g. d = 1,663,370 for t in range(rounds): m = max(int(C * K), 1) S = random.sample(range(K), m) # this round’s clients results = [client_update(k, w) for k in S] # in parallel on the phones m_t = sum(n[k] for k in S) w = sum((n[k] / m_t) * wk for k, wk in zip(S, results)) # weighted average of models # ClientUpdate(k, w) runs on client k def client_update(k, w): batches = split(P[k], B) # shuffled, size B (or one batch if B = inf) for epoch in range(E): for b in batches: w = w - lr * grad_loss(w, b) # ordinary SGD step return w # same shape as the w it received
Read the server half first. Pick m = max(C·K, 1) clients at random. Send each the current w. Collect the returned models. Average them with weights nk / mt, where mt is the total number of examples held by this round’s clients. The weights again add to 1.
A numbers-only round, with a one-weight model. Three clients are chosen, holding 600, 300 and 100 examples, so mt = 1,000. All start at wt = 1.0. After local training they return 0.6, 0.9 and 1.4. Then:
wt+1 = 0.6 × 0.6 + 0.3 × 0.9 + 0.1 × 1.4 = 0.36 + 0.27 + 0.14 = 0.77
The big client pulls the result most. Walk a round on the toy from the last chapter and watch the same thing happen.
Press Next stage to move through the four stages, or Run a round to watch them all. Drag the local steps to change E. The more steps each client takes, the farther one round carries the model.
Toy, not from the paper: the same three bowl-shaped client losses as the last device (data shares 600, 300 and 100), full-batch local steps (B = ∞) with learning rate 0.3. The paper’s real clients use minibatches of a neural network.
With one local step the model creeps. With ten it jumps most of the way in a single round. This is the paper’s whole bet. The next-to-last stage is the only one that touches the network, and each round has exactly one of it.
For the MNIST CNN, the server sends one vector of shape [1,663,370] to each of 10 clients: about 6.7 MB each at 4 bytes per weight. Each client trains on [600, 28, 28, 1] images and returns one vector of the same shape. FedAvg and FedSGD send exactly the same number of bytes per round. FedAvg wins only by needing fewer rounds. This is why the paper counts rounds and not seconds.
One failure is worth naming now. The symptom: the global model stays near chance accuracy for many rounds. The cause could be a server that gave each client a different random starting model, so that the averaged weights are a blend of unrelated networks. The measurement is Chapter 4’s left-hand curve. The fix is the single line at the top of the server loop: initialize w once and send the same vector to everyone.
Chapter 4
Test the worry that averaged weights are nonsense, and find out what a shared starting point changes
Two students each write an essay on the same topic. One opens with the argument and ends with the example. The other does the reverse. Now average the two essays word by word. You do not get a good essay. You get mush, because the pieces that matched by position did not match by meaning.
A neural network has the same trap. Its hidden units are interchangeable: if you swap two of them, and swap the weights that connect to them, the network computes exactly the same function. So two networks that learned the same thing can store it in different slots. Average them slot by slot and you blend unrelated parts. For general non-convex problems, the paper warns, averaging “could produce an arbitrarily bad model.”
Yet FedAvg averages models in the weight space every round. Why does it work? The paper runs one small experiment that answers it.
Take two models with weights w and w′. Mix them with a mixing weight θ:
Worked on two tiny models, w = [0.2, 0.8] and w′ = [0.6, 0.4]. At θ = 0.5 the mix is [0.4, 0.6]. At θ = 1.2, which goes past w, the mix is [1.2·0.2 − 0.2·0.6, 1.2·0.8 − 0.2·0.4] = [0.12, 0.88]. The paper sweeps θ from −0.2 to 1.2 in 50 even steps and measures the loss of every mix on the full training set. Plotting loss against θ draws the loss along the straight line between the two models.
The setup, as the paper gives it: two MNIST 2NN models, each trained by SGD on its own non-overlapping IID sample of 600 examples. Learning rate 0.1, minibatches of 50, 240 updates, which is 20 passes over the 600 examples. That is about the point where the models start to overfit their small sets. The only difference between the two panels of Figure 1 is how the two models began.
With independent initialization, each model started from its own random weights. The loss in the middle of the line climbs far above either end. With common initialization, both started from the same random weights. Then the middle of the line is low. The paper reports that the plain average “achieves significantly lower loss on the full MNIST training set than the best model achieved by training on either of the small datasets independently.”
Try the same contrast on a toy you can train in your browser: a small network with six hidden units, fitted to a noisy curve from 20 points per model.
The warm curve is the loss along the line between two networks that began from the same weights. The pink curve is the same for networks that began from different weights. Drag θ and read both losses. Press Train new pair for another random start.
Toy, trained live in your browser and not from the paper: a 1-input network with 6 tanh hidden units fitted to y = sin(2x) + 0.3x with noise, 20 points per model, 600 full-batch steps at learning rate 0.05. The loss is measured on all 40 points, on a log axis. Results vary with the seed: the paper’s real MNIST figure shows the shared-start average beating both parents, and in this toy the shared-start average usually lands near the better parent, and sometimes below it.
The pink curve is the lesson. Its ends are low, because each model is good. Its middle is high, often by a factor of ten or more, because the average of two differently organized networks is a mess. The warm curve stays near the level of its ends. Models that start together stay in the same region, so their slots keep their meanings, and mixing them blends similar parts.
Look at line 1 of Algorithm 1: the server runs initialize w_0 once and sends that single vector to everyone. In every later round each client starts from the current global model wt. So all the models being averaged share a starting point, which is exactly the right-hand panel. The paper says it directly: “a shared starting model wt is used for each round of FedAvg, and so the same intuition applies.”
The paper also leans on research saying the loss surfaces of large neural nets are better behaved than once feared. Treat that as the paper’s argument and not as a proof. FedAvg has no guarantee here. It works because the experiments say so, and Chapters 5 to 7 are those experiments.
One more thing the paper guesses at: averaging may also act like regularization, a pull against overfitting similar to dropout. The paper offers this as a conjecture. Its evidence is that FedAvg reaches higher final accuracy than FedSGD. For example, the CNN trained with FedSGD reaches 99.22% after 1,200 rounds and no better after 6,000. FedAvg with B = 10 and E = 20 reaches 99.44% after 300 rounds.
Chapter 5
Read the paper’s main tables, and learn which knob, E or B, buys the most
You run a kitchen with one slow delivery truck. The truck is the bottleneck, but the cooks are idle. So you stop sending the truck out for every dish. Instead you let each cook prepare a whole tray before the truck leaves. You spend idle cook time to save truck trips. The numbers in this chapter show how many trips that saves.
The paper's two main result tables, Table 2 for the MNIST CNN and the Shakespeare LSTM, and Table 4 in the appendix for the MNIST 2NN, all do the same thing. They fix C = 0.1 and vary the work per client. They report how many communication rounds each setting needs to reach a target test accuracy: 99% for the CNN, 97% for the 2NN, 54% for the Shakespeare model.
The rows are sorted by u, the expected number of local updates per client per round. Chapter 3 gave its formula. Here is how it plays out on a row from Table 4, the 2NN with E = 10 and B = 50 on 100 clients of 600 examples:
u = E · n / (K · B) = 10 × 60,000 / (100 × 50) = 10 × 12 = 120
Two knobs raise u. A larger E makes more passes over the same data. A smaller B cuts each pass into more, smaller steps. The first row of each table is FedSGD (E = 1, B = ∞, u = 1), and the other rows are FedAvg. The little number beside each result, like 31.3×, is the speedup over that FedSGD row.
The paper is careful here, and so should you be. The learning rate matters a lot, so for every setting it tries a grid of 11 to 13 learning rates (steps of 101/3 or 101/6 apart) and keeps the best. It checks that the best rate is in the middle of the grid. It draws each learning curve, makes it monotone by taking the best accuracy seen so far, and finds where it crosses the target by linear interpolation. Over 2,000 individual models were trained for these experiments. Treat every number as the best of a tuned sweep, not of one lucky run.
Pick a model. Each row is one setting of E and B, sorted by local updates per round (u). The solid blue bar is IID data. The pale blue bar is non-IID. Drag the row selector to read one row in full.
All numbers are the paper’s: Table 2 (CNN and LSTM) and Table 4 (2NN), C = 0.1, best learning rate per row. The Shakespeare IID column is a balanced version of the same text; the non-IID column splits it by speaking role. The u values for the LSTM are the paper’s, which are not whole numbers because clients hold different amounts of text.
On IID MNIST, the picture is clear. For the CNN, FedSGD needs 626 rounds. The best row, E = 20 and B = 10 with 1,200 updates per round, needs 18: a 34.8× saving. For the 2NN it is 1,468 rounds down to 32, a 45.9× saving. The paper's summary: “using more computation per client decreases the number of rounds to reach the target accuracy by 35× for the CNN and 46× for the 2NN.”
Three details are worth your attention. First, B pays more than E. For the CNN with full batches, going from E = 5 to E = 20 raised rounds from 179 to 234. Cutting B to 10 at E = 5 dropped them to 20. Smaller batches give more steps for the same number of passes. The paper's advice follows: as long as B is big enough to use the phone's hardware well, lowering it costs almost no extra time, so “this should be the first parameter tuned.”
Second, returns flatten. On the CNN, 60 updates per round needs 29 rounds, and 240 needs 32. The curve is not strictly falling. Going from 300 to 1,200 updates saves only 2 rounds. Past a point you spend more computation for nothing.
Third, this is not a free lunch on total compute. The paper's Figure 9 compares accuracy against the number of minibatch gradients computed. For modest C and E, FedAvg makes about the same progress per gradient as ordinary sequential SGD. So FedAvg does not do the same work with fewer steps. It does the same work in a form that needs far fewer network trips.
Look at the pale bars. The non-IID column is far less impressive. On the CNN with E = 5 and full batches, FedAvg takes 1,000 rounds against FedSGD’s 483, a speedup of 0.5×. It is slower. Row 3 of the CNN table, E = 1 with B = 50, is also slower at 0.8×. The best non-IID rows get 2.8×, still a good gain but small beside 34.8×. Chapter 6 asks why. The Shakespeare model, on the other hand, gets 95.3× on its natural non-IID split, and Chapter 6 explains that too.
Chapter 6
See what the paper found when clients disagree, and why more local steps can push the average off target
Ten choir members each rehearse their own part at home for a week, then meet to blend. If everyone sang the same song, a week of solo practice helps the blend. If each singer practised a different song, a week of solo practice makes the blend worse. The longer they practise alone, the more each voice drifts toward its own piece. FedAvg faces the same tension. This chapter is about when local work helps and when it hurts.
Table 1 varies C, the client fraction. In the table, C = 0.0 means one client per round, and with 100 clients the rows are 1, 10, 20, 50 and 100 clients. The results depend on B:
The paper settles on C = 0.1 for most tests, “a good balance between computational efficiency and convergence rate.” The takeaway is simple. When clients differ a lot, hearing from more of them each round steadies the average. A single client per round also makes the accuracy curve swing, which the paper sees for both plain SGD and FedAvg at C = 0.
Recall the MNIST split where each client sees only two digits. The paper calls it pathological on purpose, to see how far the method can bend. On the CNN, three FedAvg rows are slower than FedSGD, as Chapter 5 showed. But the best rows still gain 2.8 to 3.7 times. The authors write that “it is impressive that averaging provides any advantage (vs. actually diverging) when we naively average the parameters of models trained on entirely different pairs of digits.”
The natural split of Shakespeare gives a twist. Here each of 1,146 clients is one speaking role in a play, with at least two lines. That data is both non-IID and unbalanced: some roles have a handful of lines and a few have a great many. You might expect this to be harder. It is easier. The best FedAvg setting needs 41 rounds against FedSGD’s 3,906, a 95.3× saving. On the balanced IID version the same setting gets 13.0×.
The authors guess the reason: some roles hold a lot of text, so extra local training is especially valuable for them. Their guess, not a proven fact.
Figure 3 trains the Shakespeare LSTM with very many local epochs per round. The result: “for very large numbers of local epochs, FedAvg can plateau or diverge.” On the CNN the paper sees no real loss from large E (its Figure 8). On the big word model, E = 1 does slightly better than E = 5. The paper’s remedy is practical: late in training, shrink the local work (smaller E or larger B), just as you would decay a learning rate.
The paper gives a short reason why very large E must stop paying off. A client’s result depends on the start point only through the weights it was handed. As E grows, each client tends toward the best model for its own data and forgets where it began. Averaging many such models then gives you something fixed by the clients’ own optima.
Here is a worked case on one weight, an illustrative toy, not from the paper.
Two clients hold equal data. Client A’s loss is a bowl with its bottom at 0 and curvature 1. Client B’s bottom is at 1 and curvature 3. The global best is where the combined slope is zero: ½w + ½·3(w − 1) = 0, which gives w = 0.75. With E = 1, FedAvg converges to exactly 0.75. With huge E, A returns 0 and B returns 1, so the average is 0.5. That is off target by 0.25, and more training will not fix it. The bias exists because the server weights clients by data share, but the best compromise weights them by how sharp their bowls are as well.
The curve shows how far FedAvg’s resting point lies from the true best weights, for each number of local steps. Drag the first slider to move along it. Drag the second to make the clients agree more or less.
Toy, not from the paper: the three bowl-shaped clients from Chapters 2 and 3 (data shares 600, 300 and 100, curvatures 1, 2 and 0.5, learning rate 0.3). The resting point is the exact fixed point of the round map, found in closed form: each local run shrinks the distance to the client’s optimum by (1 − 0.3a)E. The paper only observes that large E can stall or diverge on its LSTM; the bias shown here is one simple reason, later studied by other work.
At E = 1 the gap is exactly zero: that is FedSGD, and it lands on the best weights. As E grows the gap rises and flattens. Squeeze the second slider toward zero and the curve flattens onto the axis. When the clients agree, extra local work costs nothing. That matches the table: IID data enjoys large E, and non-IID data does not.
This also frames the trade the paper makes. In real networks the paper’s tests still show a large net gain, because early in training the model is far from any optimum and every local step is useful. The danger shows up late, near the end, which is why the paper suggests decaying the local work.
Chapter 7
Check the claim on CIFAR-10 and on a language model with half a million clients, then list the limits
A method that wins on MNIST has proved little, because MNIST is tiny and easy. A careful reader asks two questions. Does the win survive a harder task? Does it survive data that looks like the real thing? The paper answers with two more experiments, then says plainly what it left out.
CIFAR-10 is 60,000 small color images (32×32 pixels, three color channels) in ten classes. The paper splits the 50,000 training images over 100 clients with 500 images each, and gives each client 100 test images. There is no natural user split here, so the data is balanced and IID. The model comes from the TensorFlow tutorial: two convolution layers, two fully connected layers, and a linear layer, about 106 parameters. Images are cropped to 24×24, flipped at random, and adjusted for contrast and brightness.
This test adds a third opponent: plain sequential SGD on the full training set with minibatches of 100. In the federated setting every one of those minibatch updates would be a round, so its count of updates is its count of rounds. FedSGD and FedAvg use C = 0.1. FedAvg uses E = 5 and B = 50, so each client makes u = 50 updates per round. All three tune a learning-rate decay on top of the learning rate. Table 3 gives the rounds to reach three accuracy targets.
Pick a target. Bars use a log scale, because the gaps span more than 60 times. The pink bars are the baselines and the warm bar is FedAvg.
CIFAR numbers are the paper’s Table 3; SGD’s count is minibatch updates, each of which would be one round. FedSGD did not reach 85% (the paper prints N/A). The word-LSTM numbers are from the paper’s text: FedSGD (learning rate 18.0) needed 820 rounds to reach 10.5% and FedAvg (learning rate 9.0, B = 8, E = 1) needed 35, with 200 clients per round. The time estimate assumes about 106 weights at 4 bytes and 1 MB/s, and is illustrative.
The picture is steep. To reach 80%, sequential SGD needs 18,000 rounds, FedSGD 3,750 (4.8×) and FedAvg 280 (64.3×). To reach 85%, SGD needs 99,000 rounds, FedSGD never gets there in the paper’s runs, and FedAvg needs 2,000 (49.5×). Put into the time units of Chapter 0, a 4 MB upload at 1 MB/s takes about 4 seconds. At that rate 2,000 rounds is about 2.2 hours of uploads and 99,000 rounds is about 110 hours. The shape of the curves is shown in Figure 4. FedAvg also ends at a similar accuracy to SGD: 85% after 2,000 rounds, against 86% after 197,500 minibatch updates.
The last test is the closest to the real use. The data is 10 million public posts from a large social network, grouped by author into over 500,000 clients, with each client capped at 5,000 words. The model is a next-word LSTM: a vocabulary of 10,000 words, 192-number word vectors, a 256-node LSTM, 4,950,544 parameters in all. The score is the share of positions where the model’s top guess is the right next word, out of 10,000 choices, on 100,000 posts from different authors.
Every run used 200 clients per round. FedAvg used B = 8 and E = 1. The paper says these runs needed “significant computational resources” so it explored fewer settings. Even so, FedSGD at its best learning rate needed 820 rounds to reach 10.5% accuracy, and FedAvg needed 35: 23 times fewer. FedAvg’s test accuracy also varied less from round to round. Here E = 5 did a little worse than E = 1.
Notice what FedSGD does on this task. The symptom: it climbs steadily but slowly, and by round 6,600 it has only reached 82%. The measurement: at 85% it has no entry in Table 3 at all, so the paper prints N/A. The fix, once more, is more local work per round, and that is what FedAvg's 2,000 rounds buy.
Read this list as a careful reviewer. Some items are the paper’s own statements, and the last are my reading.
Chapter 8
Keep the numbers, the terms, the checklist and the code, and follow the bridge to compute islands
The paper makes one move. When the network is the bottleneck, let each client do a lot of work before it speaks. Each client starts from the server’s weights, runs E epochs of minibatch SGD, and uploads its model. The server averages the models by data share. That cut the rounds needed by 10 to 100 times on the paper’s tests, and the gain was smaller but real on data where clients disagree.
| What | Value | Where in the paper |
|---|---|---|
| MNIST setup | 100 clients × 600 examples; non-IID = 2 digits per client | Section 3 |
| Client fraction used | C = 0.1 (10 clients per round) | Table 1 discussion |
| Model sizes | 2NN 199,210; CNN 1,663,370; char LSTM 866,578; word LSTM 4,950,544 | Section 3 |
| MNIST CNN, IID, 99% | 626 rounds (FedSGD) → 18 (E = 20, B = 10): 34.8× | Table 2 |
| MNIST 2NN, IID, 97% | 1,468 → 32: 45.9× | Table 4 |
| MNIST CNN, non-IID, 99% | 483 → 173: 2.8× (some rows slower than FedSGD) | Table 2 |
| Shakespeare LSTM, 54% | IID 2,488 → 192 (13.0×); by role 3,906 → 41 (95.3×) | Table 2 |
| CIFAR-10, 85% | SGD 99,000; FedAvg 2,000 (49.5×); FedSGD N/A | Table 3 |
| Word LSTM, 10.5% | 820 rounds → 35: 23×; over 500,000 clients | Section 3 text |
| Term | Meaning |
|---|---|
| Client | A device that holds some data and trains on it. In the paper, a phone. |
| Round | The server sends out the model, clients train, clients upload, the server averages. The unit the paper counts. |
| FedSGD | One gradient step per round. The baseline. |
| FedAvg | Many local steps per round, then a data-weighted average of the models. |
| C, E, B | Share of clients per round; local epochs; local minibatch size. |
| u | Local updates per client per round, E · n / (K · B). |
| IID / non-IID | Every client sees the same mix of data / clients see different mixes. |
| Unbalanced | Clients hold very different amounts of data. |
| Pseudo-gradient | The change a client or group makes to the weights, treated as if it were a gradient. Defined below. |
python import numpy as np def client_update(w, X, y, grad, E, B, lr, rng): w = w.copy() # [d] n, bs = len(X), (B or len(X)) # B = None means one full batch for _ in range(E): idx = rng.permutation(n) for s in range(0, n, bs): b = idx[s:s + bs] w -= lr * grad(w, X[b], y[b]) # ordinary SGD step on a minibatch return w # [d] def fedavg(w0, clients, grad, rounds, C, E, B, lr, rng): w, K = w0.copy(), len(clients) for t in range(rounds): S = rng.choice(K, max(int(C * K), 1), replace=False) n = np.array([len(clients[k][0]) for k in S], float) # [m] Wk = np.stack([client_update(w, *clients[k], grad, E, B, lr, rng) for k in S]) # [m, d] w = (n[:, None] / n.sum() * Wk).sum(axis=0) # weighted average, [d] return w
Rohan Anil’s post says federated learning “added two more ingredients” to the older local-update idea: “treat each worker’s parameter change between exchanges as a pseudo-gradient, and apply a separate outer optimizer to it.” You can see both inside FedAvg. Define the pseudo-gradient as the average change the clients made:
Check it with the Chapter 3 numbers: wt = 1.0 and the clients returned 0.6, 0.9, 1.4. Then Δ = 0.6×0.4 + 0.3×0.1 + 0.1×(−0.4) = 0.23, and 1.0 − 0.23 = 0.77, the same result as before. The post’s timeline credits the next steps to later work: FedAvgM and FedOpt put momentum or adaptive steps in that outer slot, and SlowMo is named as a precursor of DiLoCo’s outer optimizer.
The compute-islands setting differs from the paper’s in ways that change what to expect (my reading). The “clients” are whole clusters, so there are few of them. Their data can be shuffled to look alike, so the IID case matters more than the pathological one. And the local work is enormous, so the late-training drift from Chapter 6 is the thing to watch.
Now press Present or Teach and explain FedAvg from memory: why the round is the cost, why averaging models equals a gradient step when E = 1, why a shared start makes averaging safe, and why non-IID data weakens the gain. Then go back to the race at the top, switch to non-IID, and explain why the first row is slower than the baseline.
Credit: H. Brendan McMahan, Eider Moore, Daniel Ramage, Seth Hampson and Blaise Agüera y Arcas, “Communication-Efficient Learning of Deep Networks from Decentralized Data”, AISTATS 2017, arXiv:1602.05629. All tables are the authors’ numbers; the toys, the worked examples and the code are ours.