Moshpit SGD

A swarm of unreliable computers must agree on one average. Moshpit All-Reduce splits the swarm into small groups that reshuffle every round, so a crash ruins one group, not the run.

Learn how many cheap, flaky, slow-linked machines can train one neural network together, and why the trick is a grid of small groups.

Raise the failure rate, then switch the swarm size. Watch which method keeps shrinking its error. Then we build, piece by piece, everything underneath: all-reduce, the grid, the phone book that forms groups, the proof, the training loop and the results.

You need what an average is and that a neural network learns by small steps. We build the rest from zero.

Paper: Max Ryabinin, Eduard Gorbunov, Vsevolod Plokhotnyuk and Gennady Pekhimenko, “Moshpit SGD: Communication-Efficient Decentralized Training on Heterogeneous Unreliable Devices”, NeurIPS 2021. Read with the Core Automation post The Hitchhiker’s Guide to Training on Compute Islands. Background: decentralized and gossip training. Re-taught here in our own words and devices.

Average a failing swarm

0.50%

A real simulation, not a recording: every peer starts with a random number, and each method tries to bring all peers to the true average. Error is the mean squared distance from that average, averaged over 6 runs on a log scale. Moshpit uses a grid of groups (8×8, 8×8×8 or 32×32 as in the paper’s Section 4.1); a group skips its round if any member fails. Gossip is a toy ring where each peer averages with its two neighbours. All-reduce shows its expected tries per good round. Paper setup: Section 4.1, Figure 3, Table 4.

Chapter 0

Why Averaging a Swarm Breaks

See why one dead computer can stall a whole training run, and what we would like instead

Picture a rowing boat with 1,024 rowers. Every stroke, all of them must finish together before the boat moves on. Now one rower drops an oar. The whole boat waits. With 1,024 rowers, somebody drops an oar almost every stroke.

That is the problem this paper solves. To train a big neural network, many computers share the work. At the end of each step, they must agree on one number per weight: the average of what each computer found. If one computer is late or dead, the others wait.

The words we need, one at a time

A neural network is a big function with millions of adjustable numbers, called weights. Training means nudging the weights, step after step, so the network makes fewer mistakes. Each nudge comes from a gradient: for every weight, a number that says which way to push it. The recipe that follows the gradient is SGD, stochastic gradient descent. “Stochastic” means each gradient is computed from a small random batch of examples.

One computer is too slow for a big network. So we use data parallel training: every computer holds a full copy of the weights, takes its own slice of the batch, and computes its own gradient. Then all computers average their gradients (add them up and divide by how many there are), and all apply the same update. The paper’s introduction calls this the dominant approach.

The averaging step is the hard part. The computers talk over a network, and a network has limited bandwidth: how many bits per second a link can carry. Think of bandwidth as the width of a pipe. A pipe of 1 Gb/s (one gigabit per second) moves about 125 megabytes each second. A network with 100 million weights needs to move 400 megabytes of 32-bit numbers per computer per step, so a thin pipe is slow.

Two ways to average, and why both hurt

The oldest way is a parameter server: one special computer that collects every gradient, averages them, and hands back the result. It is simple and robust. But it must receive full gradients from everybody. With hundreds of workers, the server’s pipe becomes the bottleneck. The paper notes it can quickly limit large-scale training.

The modern way is all-reduce. There is no server. The computers pass pieces of their vectors among themselves in a clever pattern, so each ends with the full average. Each computer sends only about as much data as one gradient, no matter how many computers there are. That is why the paper says all-reduce has a “constant communication overhead”. The catch: the pattern needs every computer to show up on time. If any one fails or runs slow, all others stall.

Big labs avoid the catch with expensive, dedicated networks. This paper asks about the opposite world. Cheap preemptible cloud machines can be taken away at any moment, but cost about three times less (paper, Appendix A, Table 1). Volunteers’ PCs, phones in federated learning (training on devices that keep their private data), and leftover GPUs in many places all share one trait: they are unreliable and heterogeneous, meaning they differ in speed and in network. The Core Automation post calls such scattered pools “compute islands”.

There is a third method for that world: gossip. Each computer only talks to a few neighbours and averages with them, round after round. Information spreads slowly through the graph, like a rumour. It tolerates failures. But with hundreds of peers it needs many rounds, or many neighbours, which costs bandwidth. The background lesson on gossip training builds that idea in full.

Feel how fragile one big group is

Let each peer fail in a given round with chance p. A round of whole-swarm all-reduce works only if all N peers survive. That happens with chance (1 − p)N. The curve below plots that for any group size k. Slide the swarm size and failure rate. Then compare with a group of 32.

Count the survivors

The curve is the chance that a group of k peers all survive one round. The purple dot is the whole swarm as one group. The warm dot is a group of 32, the size the paper uses.

1,024
0.50%

The formula (1 − p)k assumes peers fail independently and a failed peer ruins its whole group for that round. The paper’s own all-reduce baseline restarts more cleverly: Table 4 reports 42.6 iterations for N = 1,024 and p = 0.005, where the simple “start over” count here is higher.

At 1,024 peers and 0.5% failures, a clean round is a rare event, about one in 170. A group of 32 survives about 85 times in 100. That gap is the whole idea of the paper: never ask everybody to succeed at once. Make small groups. Let a crash cost one group one round. Then mix the groups so that, over a few rounds, everyone still ends up with the global average.

The authors name the result Moshpit All-Reduce, after the crowd at a concert that forms small circles and keeps changing partners. They build Moshpit SGD on top: ordinary training with a Moshpit average inside it. The paper reports 1.3 times faster ResNet-50 training than the best gossip methods and 1.5 times faster ALBERT-large pretraining on preemptible machines.

The road

  1. Averaging without a boss: butterfly all-reduce, step by step, and what it costs per computer.
  2. Averaging in small groups: the grid, one axis at a time, and the exact average.
  3. Finding your group: a shared phone book, a leader, and agreement on who is in.
  4. Why broken groups still converge: the proof, in plain steps, with a number.
  5. Training with local steps: Moshpit SGD, the algorithm, and the communication it saves.
  6. Sharing work by bandwidth: a small linear program that sizes each peer’s slice.
  7. A swarm that joins and leaves: pooled batches, early matchmaking, pseudo-gradients.
  8. What the tables and figures show: Table 4, ImageNet, ALBERT, and the limits.
  9. The field guide: numbers, terms, code and where to go next.
Why does whole-swarm all-reduce get worse as you add more cheap, unreliable machines?

Chapter 1

Averaging Without a Boss

Follow butterfly all-reduce step by step and see why it is fast, and why it is fragile

Three friends each hold a list of three numbers. They want every friend to end with the average list. There is no boss to collect and hand out. How do they do it with the least talking?

A first idea: everyone sends their whole list to everyone else. That works, but each friend sends two full lists. With 1,000 friends, each sends 999 lists. The talking grows with the group. We want a plan where each friend sends about one list in total, however many friends there are.

Split, send, average, share back

The paper’s Figure 1 shows Butterfly All-Reduce. It has four moves. First, each of the N workers splits its vector (the long list of weights or gradients) into N equal chunks. Second, in the scatter move, every worker sends chunk j to worker j. Third, in the reduce move, worker j averages the N copies of chunk j it received. Fourth, in the all-gather move, worker j sends its averaged chunk to everyone. Now every worker holds all N averaged chunks, which is the full average vector.

Step through it below. The numbers are small on purpose, so you can check every sum by hand.

Step through butterfly all-reduce

Three workers, three chunks each. Press Next move and watch where each number goes. Then drag the worker count to see what each worker uploads.

64

Toy numbers: W1 = [3, 6, 9], W2 = [6, 0, 3], W3 = [0, 3, 0], so the average is [3, 3, 4]. The upload figures use an illustrative 1 GB vector and the paper’s cost of s(N−1)/N per move (Section 2.2).

Count what each worker sends. In the scatter move, it keeps one chunk and sends N − 1 chunks, each of size s/N, where s is the vector size. That is s(N−1)/N, always a little under s. The all-gather move sends the same amount again. So the cost per worker does not grow with N. The paper writes this as O(s × (N−1)/N) bandwidth per worker. A parameter server, by contrast, must receive N full vectors.

The table below shows the real data flow for a model with n weights stored as 32-bit floats. Nothing here is special to the paper. It is the standard idea, and the data parallel and all-reduce lesson goes deeper.

MoveWho sendsMessage shapeAfter the move
Splitnobody[n] into N pieces of [n/N]each worker has N chunks
Scatterevery worker, to N−1 others[n/N] eachworker j holds N copies of chunk j
Reducenobody (local math)noneworker j holds the average of chunk j
All-gatherevery worker, to N−1 others[n/N] eacheveryone holds [n], the full average

Let us put real sizes on it. A model with 100 million weights stored as 32-bit numbers is a vector of 400 megabytes. With 8 workers, each chunk is 50 megabytes. In the scatter move, each worker sends 7 chunks, which is 350 megabytes. In the all-gather it sends 350 more. Move to 64 workers and the chunks shrink to about 6 megabytes, but each worker sends 63 of them, about 394 megabytes per move. The load per worker barely changed, even though the swarm grew eightfold. That flatness is why every large training system uses some form of all-reduce.

Time matters too. At 1 Gb/s a worker moves about 125 megabytes each second. Uploading 350 megabytes takes close to 3 seconds. All 64 workers upload at the same time, each over its own link, so the wall-clock cost is about the time of one worker, not 64 times that. A server with one 1 Gb/s link, receiving 64 vectors of 400 megabytes, would need over 200 seconds. This is the gap between “each worker pays about one vector” and “one machine pays all of them”.

Where it is fragile

Worker j is the only one that averages chunk j. Press Kill worker 2 in the device and step again. Chunk 2 never gets averaged. Nobody can finish the vector. The other two workers wait forever for a message that will not come, or they must throw away the round and start again.

There is a second problem. In the scatter move, every worker talks to every other worker. In a big data centre, that all-to-all traffic can jam the switches. So real systems often use Ring All-Reduce (each worker only talks to its two neighbours in a circle) or Tree All-Reduce (workers form a tree). The paper says these use O(1) or O(log N) communication per worker. They are also even less forgiving. A broken link in a ring breaks the ring.

Here is the key observation behind Moshpit. Butterfly all-reduce is exact and cheap for a small group. The danger comes from running it on a huge group where something is always failing. So keep the group small, and find another way to reach everyone.

pythonimport numpy as np
def butterfly_allreduce(vecs):                     # vecs: list of N arrays, each shape [n]
    N = len(vecs)
    chunks = [np.array_split(v, N) for v in vecs]    # split: N chunks per worker
    mine = [np.mean([chunks[i][j] for i in range(N)], axis=0)   # scatter + reduce: worker j averages chunk j
            for j in range(N)]
    full = np.concatenate(mine)                      # all-gather: everyone gets every averaged chunk
    return [full.copy() for _ in range(N)]
In butterfly all-reduce with N workers, what does worker 4 do during the reduce move?

Chapter 2

Averaging in Small Groups

Place peers on a grid and average along one axis at a time to get the exact mean

Nine friends stand in a 3 by 3 square. Each holds one number. They want everybody to learn the average of all nine. Big meeting of nine? Too fragile. Instead they average in threes.

Round one: each row of three averages together. Each person in the row now holds the row’s average. Round two: each column of three averages together. Look at the second round. Every column holds one person from each row, and each row has already merged into one value. So averaging the column averages the three rows. That is the average of all nine. Two rounds, groups of three, an exact answer.

Why the exact answer comes out

Let the peers sit at grid coordinates (j1, j2). Their numbers are θj1 j2. Round one averages along the first axis, so every peer in a row gets (1/M) Σj1 θj1 j2. Round two averages that along the second axis. Write both rounds as one formula and the sums merge:

θd
The value every peer holds after d rounds of averaging, one round per grid axis.
1/Md
One over the total number of peers. A grid with M positions on each of d axes holds Md peers.
Σj1,…,jd
Add over every coordinate on every axis. This visits each peer exactly once.
θj1…jd
The starting value of the peer at that grid position.

This is the paper’s Theorem C.1: in a full grid with no failures, d rounds give the exact global average. The proof expands the nested averages and notices that each starting value appears once in the final sum. With M = 3 and d = 2, nine peers need two rounds. With M = 32 and d = 2, 1,024 peers need two rounds, and no group has more than 32 members. In Table 4, Moshpit reaches 2.0 rounds for N = 1,024 with no failures, exactly this.

Try it. The nine numbers are 9, 3, 6, 0, 12, 3, 15, 6, 0, which average to 6. First step with everyone alive. Then press Reset, mark a peer as failed, and step again.

Average a 3 by 3 grid

Press Next round twice. Round one groups the rows, round two groups the columns. Toggle a numbered button to make that peer fail before you start.

Toy numbers. Here a failed peer sits out the whole run, and its group averages the peers that remain, which is what happens when a peer is missing at matchmaking time. A peer that dies during the all-reduce itself makes its group skip the round instead (paper, Section 3.1).

With everyone alive you get 6 for all nine peers. Now fail peer 5 (the 12). Row two averages only 0 and 3, giving 1.5. The columns then give 4.83, 6.5 and 4.83. Nobody holds 6, and peer 5 still holds 12. The paper notes this: with holes in the grid the result is only close to the average. But the total never changes. The sum of all values is still 54. Averaging inside a group moves numbers around but never creates or destroys any. That is the invariant the proof of Theorem 3.1 uses.

Why bother with a grid, if one big group gives the answer in one round? Because the group size is the failure surface. In a grid you choose how to split the swarm: M peers per axis and d axes, with Md about equal to the swarm size. For 1,024 peers you could choose 32 × 32 (groups of 32, 2 rounds), or 45 (groups of 4, 5 rounds), or 210 (pairs, 10 rounds). Smaller groups survive failures more often, and cost more rounds. The paper’s Appendix I tests exactly this for a million peers, arranged as 10242, 324 and 410 grids, and finds that M = 32 was best only at one particular failure rate.

Staying in different groups: the key

In real life there is no square. Peers join, leave and fail. We need a rule that creates the same effect without any global plan. The rule: if two peers shared a group in round t, they must land in different groups in round t+1. Averaging again with the same people wastes a round, since you already agree.

The trick uses the chunk numbers from butterfly all-reduce. Recall that worker j ends a group round as the owner of chunk j. In a group of M peers, each peer has a different chunk index. If peers use that index as their next group label, then peers who were together now carry different labels. The paper writes a peer’s group key as a tuple of its recent chunk indices:

Cit
The group key of peer i at round t. Peers with the same key meet in one group.
cit−d+1, …
The chunk indices peer i held in earlier rounds, going back so the tuple has d−1 entries (paper, Equation 1).
cit
The chunk index peer i got in the latest group, a number from 0 to M−1.

Peers start with coordinates read from their index: write the peer number in base M and take the digits. The paper’s get_initial_index does this, so the first groups hold at most M peers (Equation 2). After that, the grid is not stored anywhere. It is rebuilt every round from the keys that peers carry. A key is just a few small numbers. That is all a peer needs to remember.

1,024 peers sit in a full 32 by 32 grid, with no failures. How many rounds give the exact average, and how big is each group?

Chapter 3

Finding Your Group Without a Server

Use a shared phone book and a first-come rule to form groups that agree on their members

Imagine 1,024 strangers in a huge park, each wearing a badge with a group number. Nobody is in charge. Your job: find the other people with your badge number, quickly, even if some of them walked away. How would you do it?

You could shout. That does not scale. You could ask a central desk. That desk becomes a single point of failure, the very thing we are trying to avoid. The paper uses a shared notice board that no single person owns. It is called a Distributed Hash Table.

A phone book spread over the crowd

A hash function turns any key, like a name, into a fixed-size number that looks random. A hash table is a dictionary that uses that number to decide where to store each (key, value) pair. A Distributed Hash Table, or DHT, spreads those pairs over many computers. Each participant has a random ID. A pair (key, value) is stored on the few peers whose IDs are closest to hash(key). To read the value, you hash the key and ask the peers with the nearest IDs.

The paper uses a design called Kademlia. It measures closeness by the XOR of two IDs (XOR compares bits and marks where they differ), read as a number. Take 4-bit IDs. Say hash(key) = 1011. Peer A has ID 1001: 1011 XOR 1001 = 0010, which is 2. Peer B has 1110: XOR gives 0101, which is 5. Peer C has 0011: XOR gives 1000, which is 8. So A is closest and C is farthest. Each peer knows only a few others. To find the closest peers, it asks its neighbours for ones nearer to the key, and repeats. This takes at most O(k + log N) requests, the paper says, even for a large crowd. BitTorrent and Ethereum use the same kind of table.

Now the matching. In Algorithm 1, each round every peer computes its group key C and adds its network address to the DHT under the pair (C, round t). A peer then waits, reads the list stored under its own key, and runs all-reduce with whoever is on it. Writing and reading both cost O(log N) requests and O(M) bandwidth for the list.

Why the naive version fails

There is a trap. Suppose peer X arrives just late. Peers A, B, C already read the list and did not see X. Peer X reads the list and sees A, B, C and itself. Now X thinks the group has four members. A, B and C think it has three. They disagree about who is in, so the all-reduce cannot run in a stable way. Appendix E calls this “breaking the consensus”.

The real protocol adds three guarantees. Peers that join the same group get the same list of groupmates. The group is as large as possible unless some members fail. If members fail, the rest still form a group. To get this, each peer picks a priority: its local timestamp, plus its peer ID to break ties. A peer that wants to join calls a remote procedure call, REQUEST_JOIN_GROUP, on a neighbour with the lowest priority. That neighbour is the leader. The leader accepts or rejects.

A request is rejected if the leader is already a follower elsewhere, if the group already started its all-reduce, or if the leader left. An accepted follower promises to wait for a set time and to use the leader’s final list. So everybody in a group reads one list, the leader’s. Normally the earliest peer becomes the leader. If it dies, the group forms around the next earliest. Try the three cases:

Form a group by priority

Each bar starts when a peer announces itself in the DHT. The star is the leader, the peer with the earliest timestamp. The vertical line is when the group starts its all-reduce.

Illustrative timeline in milliseconds, not the paper’s measurements. The rules are the paper’s (Appendix E): lowest timestamp leads, ties broken by peer ID, a late or busy peer is rejected, and everyone in a group shares the leader’s list.

In the late case, nothing breaks. Peer 6 is rejected and simply tries again in the next round with a new group key. The other five all hold the identical list, so they run a clean all-reduce.

Hiding the wait

Matchmaking takes real time. The paper measured under 1 second for 64 peers in one cloud region with synchronized clocks, 2.9 seconds across two regions, and up to 9 seconds on commodity hardware around the world. Moshpit SGD hides this wait. It runs matchmaking in a background thread while the model still accumulates gradients. All peers start matchmaking 15 seconds before the estimated averaging time. In at least 95% of rounds, the group is ready by the time they need it.

Add up the costs and you get the paper’s time bound for T rounds: O(T × (log2 N + M + max(s, M) × (M−1)/M)). Read it in three parts. The log N is the DHT lookup. The M is reading the roster. The last part is the butterfly all-reduce inside one group of M with a vector of size s. Compare gossip, where the network load grows with the number of neighbours.

A peer reads the DHT list a moment after the others did and sees one extra name. Why does Moshpit not let this peer simply join?

Chapter 4

Why Broken Groups Still Converge

Derive how fast random groups shrink disagreement, and read the guarantee

Back to the park. Last chapter’s grid was perfect only when every cell was filled and nobody failed. Real swarms have holes. A friend of the method should ask: with holes, does the swarm still agree? And how fast? The paper answers with two theorems. Both rest on one simple fact.

Averaging never changes the total

When a group averages, each member gets the group mean. The group’s sum is the same before and after. So the sum over all peers never changes, and the global average stays fixed. Averaging only pulls values closer together. That is the invariant named in the proof sketch of Theorem 3.1 (correctness): if every peer has some chance of getting through each round, and group membership is random, then every peer’s value converges to the global average with probability 1.

“Converges” only says the swarm gets there. We also want to know how long it takes. That is Theorem 3.2. It studies a simplified Moshpit: each round, split the N peers at random into r groups, then average inside each group. It gives the exact rate of shrinking.

The rate, derived in plain steps

Start with a plain question. Take M numbers at random from a crowd whose average is zero, and average them. The result is closer to zero than a typical single number. With M numbers, the squared distance from zero shrinks by about a factor of M. That is how averaging cancels noise: positive and negative parts offset.

Apply that to a round. A peer joins a group of about N/r peers, and its new value is that group’s mean. So the average squared distance to the global mean drops by about N/r. The paper’s Equation 5 makes this exact:

E[…]
The expected disagreement after T rounds: the average over peers of the squared distance between a peer’s value and the global average, averaged over the random splits.
(r−1)/N + r/N²
The shrink factor for one round. It is below 1, and about r/N, one over the group size.
T
The number of rounds. The factor is applied once per round, so it is raised to the power T.
(1/N) Σ ∥θi − θ̄∥²
The disagreement at the start. θ̄ is the global average, which never moves.

Work a number. Take N = 1,024 peers and r = 32 groups (so 32 per group). The factor is 31/1,024 + 32/1,024² = 0.0303. After one round, disagreement is 3% of the start. After two rounds, 0.09%. After six rounds, about 8 × 10−10. To reach any target ε, you need T about log(1/ε) rounds. The paper says it plainly: the result holds even if workers pair up at random, and the rate does not depend on the spectral properties of the communication graph, unlike gossip.

Test the shrink factor

The line is Equation 5. The dots come from a live simulation: random splits of real random numbers, averaged over 30 runs. Change the swarm size and the number of groups.

32

Equation 5 is the paper’s Theorem 3.2, for random splits into r groups. The real Moshpit avoids repeat groupmates, so the paper expects it to do even better than this bound. Simulation: Gaussian starting values, equal-size random groups, 30 runs.

Slide r up. With more groups the groups are smaller, so each round shrinks less. With r = 1 there is a single group, and one round gives the exact average (the factor is near zero). That is plain all-reduce. Between the two ends is a dial: smaller groups mean more fault tolerance but more rounds.

Check the claim against the simulation in the device. At r = 32 the line and the dots sit on top of each other for the first three or four rounds. Later the dots may wander, because a 30-run average of a number near 10−9 is noisy. Switch to 64 peers with r = 8, groups of 8. The factor is now about 0.111. That is slower per round, and the dots follow it. Switch to r = 64, groups of 1: nobody averages with anyone, the factor is 1.0, and the line is flat. This is the right sanity check for any formula: push it to the edge where you know the answer.

The paper also says the result extends to groups of different sizes, and to a number of groups that changes from round to round, even random. That matters for a swarm where peers come and go. You do not need equal groups. You need groups that are not tiny most of the time.

What the proof does not claim

Theorem 3.2 describes averaging alone, with peers that stay alive. The authors also say that real Moshpit, which never puts the same pair together twice in a row, should converge faster than Equation 5 predicts. The proofs with vanishing peers belong to the SGD analysis in the next chapter. Notice also what the theorem does not say: it does not say how fast the training converges. That needs more assumptions.

With N = 1,024 and r = 32 groups, the shrink factor per round is about 0.03. Roughly how much of the starting disagreement is left after 3 rounds?

Chapter 5

Training With Local Steps

Combine local steps with periodic group averaging and count the communication saved

So far we averaged plain numbers. Training is different: the numbers keep changing. Every step, each peer learns a little and its weights move. If all peers averaged after every single step, they would spend most of their time talking. Is there a way to talk less?

Think of 16 hikers, each walking toward a summit using a private, slightly wrong map. If they check with each other every step, they all walk together but waste time. If they check every ten steps, each walks ten steps along its own map, then they meet and merge. They talk ten times less. The cost: between meetings each hiker drifts toward what its own map says.

Local steps, then a Moshpit average

That is local SGD: each peer runs ordinary SGD steps on its own data, and only every τ steps do the peers average their weights. The paper’s Algorithm 2 is local SGD where the average is a Moshpit All-Reduce. In words: every peer computes a gradient, takes a step, and every τ-th step the peers average the stepped weights inside Moshpit groups.

θik+1
The weights of peer i after step k. Each is a vector with n numbers, one per model weight.
MoshpitAllReducej
Algorithm 1 from Chapters 2 and 3, run across the peers j that are still alive. Peers may vanish between steps.
θjk − γ gjk
Peer j’s weights after one SGD step. γ is the learning rate and g is the stochastic gradient from its own mini-batch.
τ
The communication period. Larger τ means fewer meetings and more drift. τ = 1 means average every step.

Notice what a peer needs: its own batch, its own copy of the weights, and the ability to find a group now and then. Nobody waits for anybody between meetings. If a peer is slow, the others still run their steps. If a peer dies, its gradient is lost but the others continue, and the next average uses whoever is alive.

Run it. Sixteen peers sit in a 4 by 4 grid. Each has a different private target, a toy stand-in for different data. The swarm must find the average target. Each sync is two Moshpit rounds. Move τ and the failure rate.

Train a swarm with local steps

Thin lines are the 16 peers. The bold line is their mean. The dashed line is the true best answer. Ticks along the bottom are syncs.

5%

A toy, not the paper’s experiment: one weight per peer, fi(θ) = (θ − ai)²/2 with a different ai for each peer, learning rate 0.1, gradient noise 0.5, 60 steps. A group of 4 skips its round if any member fails.

Press Every step. The lines stay tied together, but the swarm pays 120 group rounds. Press Every 20. The lines fan out, each chasing its own target, and snap back at each sync. The final answer is nearly as good, with 6 rounds. That trade is the heart of local SGD.

Now the failure mode, as symptom, measurement and fix. Symptom: with a large τ, the loss curve of the averaged model looks fine, but single peers, seen alone, look poor. Measurement: log the largest distance between any two peers just before each sync. The device reports exactly this: at τ = 1 it stays under 1, and at τ = 20 it is above 5 in this toy. Fix: lower τ, lower the learning rate γ, or add Moshpit rounds. Each costs something, so you read the drift number and trade it against the communication you saved.

What the paper proves, in plain terms

Theorems 3.3 and 3.4 state how many steps K are needed to reach a target accuracy ε for convex and non-convex problems. The proof needs three ingredients. First, bounded variance: the noise in each stochastic gradient has an upper limit σ². Second, averaging quality: when peers meet, they are within a small distance γ²δ²aq of each other, which Theorem 3.2 delivers after enough rounds. Third, peers vanishing: the set of live peers may shrink, but not by too much, and it should keep the global average roughly where it was.

Under those conditions, if the swarm keeps a constant fraction of peers alive, Moshpit SGD needs the same number of iterations as ordinary Local-SGD with perfect averaging. The extra effect of imperfect averaging is a lower-order term. And unlike the best decentralized bounds, nothing here depends on the shape of the communication graph. The averaging steps are also much cheaper than a parameter server’s when the swarm is large.

For a full treatment of why local steps work, see the local SGD and model averaging lesson. The ancestor of the idea for devices is federated averaging, taught in its own paper lesson.

You raise τ from 5 to 20 in Moshpit SGD. What do you expect?

Chapter 6

Sharing Work by Bandwidth

Give slow peers small slices and fast peers big ones, then solve for the best split

Four friends move boxes of books to each other. One has a car, two have bikes, one walks. If everybody must carry the same number of boxes, the walker decides when you finish. A smarter plan: the walker carries few boxes, the driver carries many. That is the problem of this chapter, and the paper solves it with a small piece of arithmetic.

Real swarms are heterogeneous: peers differ in network speed, sometimes by a factor of 40. The paper says its ALBERT fleet ranged from 100 to 1,500 Mb/s per worker, and its Table 3 lists uploads as low as 25 Mb/s. A Mb/s is a megabit per second, a million bits each second, and 8 bits make a byte. In butterfly all-reduce, the plain plan gives each peer 1/M of the vector. The slowest peer then limits everyone.

Counting what each peer moves

Let a group have M peers. Peer i has bandwidth bi, defined (for simplicity, as in Appendix G) as the smaller of its upload and download speed. Let wi be the fraction of the vector that peer i averages, so the wi add up to 1. This replaces the equal 1/M split.

In the scatter move, peer i keeps its own piece and uploads everything else, that is 1 − wi of a vector. It also downloads a piece of size wi from each of the other M − 1 peers, that is (M − 1)wi. The gather move mirrors it. So the time peer i needs is proportional to the traffic divided by its bandwidth:

ti
Time for peer i to finish its communication, in units of (vector size) divided by (bandwidth).
1 − wi
What peer i uploads: its whole vector except the piece it averages itself.
(M−1) wi
What peer i downloads: its piece of size wi from each of the other M−1 peers.
1/bi
A slow link multiplies the time. This is why slow peers should get a small wi.

The whole group finishes when the slowest peer does, so the group time is the maximum of the ti. We want the split w that makes this maximum smallest, with the wi at least 0 and adding to 1. Because everything is linear, this is a linear program (LP): minimize a number ξ such that every ti ≤ ξ. The paper solves it with an interior-point solver from SciPy, scipy.optimize.linprog.

Solving it by hand

For one small group you can skip the solver. Take the condition ti ≤ ξ and solve for wi: each peer can take at most ci = (ξ bi − 1)/(M−2). A negative ci is impossible, so ξ can never be below 1/bi for any peer. Even a peer that averages nothing must still upload its whole vector once. So ξ is at least 1/bmin.

The capacities must also add to at least 1, or the vector will not fit. Setting Σci = 1 gives ξ = (2M−2)/Σbi. The best time is the larger of the two limits: ξ* = max(1/bmin, (2M−2)/Σbi). We checked this against an LP solver on several fleets. It agreed every time.

Work the ALBERT fleet: four peers with 1,000, 255, 98 and 25 Mb/s (the smaller of upload and download for four rows of Table 3). Then 1/bmin = 1/25 = 0.04, and (2M−2)/Σb = 6/1,378 = 0.0044. The first limit wins. Equal split costs (1 + 2 × 0.25)/25 = 0.06. The balanced split costs 0.04, which is one third less. For a 1 GB vector (8,000 megabits), that is 480 s against 320 s. And the slowest peer gets w = 0: it just ships its vector and does no averaging for others.

Balance the split by bandwidth

Four peers in one group. Set their bandwidths. Warm bars show how long each peer takes when the vector is split equally. Teal bars show the balanced split from the linear program.

Group of M = 4 peers and a 1 GB vector (8,000 megabits), one direction (the other mirrors it). The best time is max(1/bmin, (2M−2)/Σb), our hand solution of the paper’s Appendix G program, checked against a linear-program solver. The ALBERT preset is the smaller of upload and download for four rows of the paper’s Table 3.

The shares tell the story. Several splits reach the best time, so we pick one: each peer takes its largest allowed slice ci, scaled so the slices add to 1. In the ALBERT fleet, the 1,000 Mb/s peer then takes about 76% of the averaging work, the 255 Mb/s peer takes 18%, the 98 Mb/s peer takes 6%, and the 25 Mb/s peer takes none. Read it as a promotion rule: the fast peers act a little like servers, and the slow peers act like plain workers. When all peers are alike, the shares are all equal, and you are back to ordinary butterfly all-reduce.

Try the Equal preset: the balanced split is the same as the equal split, as it should be. Then drag one peer slow. The balanced plan quickly gives that peer a share of zero. The paper notes this interpolates smoothly between data parallelism, a parameter server and a sharded parameter server: if one peer is fast and the rest slow, it ends up doing most of the averaging, like a server.

Why can the balanced split never finish faster than 1/bmin?

Chapter 7

A Swarm That Joins, Leaves and Pools a Batch

See how a changing crowd pools a batch, matches up early, and fixes its optimizer

A bake sale needs 4,096 cookies by noon. Volunteers show up at different times, and they bake at different speeds. Some leave early. When the pile reaches 4,096, the sale starts. Nobody asks how many volunteers there were. The paper’s ALBERT run works like this, and three details make it work.

Detail one: pool the batch, not the steps

A batch is the set of examples used for one update. The ALBERT run uses a global batch of 4,096 sequences of length 512. In a fixed cluster, each of N machines takes 4096/N of them. In a swarm, speeds differ and peers come and go, so there is no fixed share. Instead, each peer keeps computing gradients on local batches and adds up its gradients. It reports its sample count to the DHT. When the swarm has collectively gathered 4,096 samples, everyone runs two rounds of Moshpit All-Reduce with groups of M = 8 and d = 2 (a grid for up to 64 peers). That is one training step.

Fast peers contribute more samples. Slow peers contribute fewer. A swarm with more peers fills the batch sooner. The paper measured this: the Moshpit iteration took 10 to 22 seconds, and moved with the number of active participants, which ranged from 30 to 66. The all-reduce baseline took a steady 25 seconds per step. The authors write that the 1.5 times speed-up comes entirely from shorter iterations; the final loss was the same within the margin of error.

Fill the global batch

Press Run one step and watch the swarm pool samples toward 4,096. Press it again, and use Preempt 20 peers while it runs to see what a mass exit does.

66

Illustrative model: each peer adds 6.2 samples per second, a rate chosen so 66 peers fill 4,096 samples in 10 s, which is the fast end of the paper’s 10 to 22 s. The slow end then comes out at about 22 s for 30 peers. The model ignores averaging time. The 25 s baseline is the paper’s (Section 4.3). The animation runs at 5 times real speed.

Why accumulate gradients instead of stepping on every small batch? Because the optimizer needs one big, steady batch to work well at this scale, and because each Moshpit average is expensive. Many cheap local batches add up to one large effective batch. The cost of a slow or missing peer is then small: the others simply fill the batch a little later. The matchmaking in the background means the group is usually ready the moment the batch is full.

Detail two: the newcomer problem

Suppose a peer joins at hour 30 of training. If it starts from the initial weights, it will average in a model that knows nothing, and drag the swarm back. The fix (Appendix F) is plain. A new peer finds a random up-to-date peer through the DHT and downloads the latest weights, the optimizer statistics and the learning-rate schedule position. The same rule applies to a peer that falls out of sync, for instance after a network freeze.

Detail three: the optimizer remembers

Many optimizers do more than subtract the gradient. Adam and LAMB (the one ALBERT uses with large batches) keep two running averages for every weight: one of recent gradients, and one of their squares. Those averages are the optimizer’s statistics, or its memory. They scale each step.

Here is the failure the paper reports. The authors tried simple parameter averaging. They averaged the weights and left the optimizer statistics alone. Training did not converge. They suspect the statistics diverged: each peer’s memory kept describing a trajectory the swarm no longer followed.

Their fix uses pseudo-gradients, an idea from earlier federated-learning work they cite. After averaging, a peer looks at how far the weights moved, from before the round to after it. It treats that movement as if it were a gradient and feeds it to the optimizer, so the statistics follow the swarm. The paper does not write the formula out, so this lesson only states the idea: the averaging step becomes one honest input to the optimizer, not an invisible jump.

The hardware behind the numbers

The swarm had 66 preemptible GPUs: 32 cloud T4 GPUs (limited to 1 Gb/s) and 34 machines from a public marketplace. They sat on three continents with 100 to 1,500 Mb/s links. It had almost three times the raw compute of the single 8×V100 baseline machine. Even so, the hourly rent was lower, at most $15.43 per hour against $24.48 for the baseline, because preemptible machines are cheap. Remember the cost: they can vanish at any time. Moshpit absorbs that. A dead peer costs one group one round.

Simple parameter averaging failed with LAMB in the ALBERT run. What did the authors change?

Chapter 8

What the Tables and Figures Show

Read the averaging table, the ImageNet run and the ALBERT run, and find the limits

A claim is only as good as the test behind it. The paper makes three tests, from small to large. First, a controlled test of the averaging alone. Second, a real image-classification run. Third, a real language-model pretraining run on rented, vanishing machines. Here is what each one shows, and what it does not.

Test one: averaging in a lab (Section 4.1, Figure 3, Table 4)

Each peer holds one number drawn from a standard Gaussian. The test counts how many rounds each method needs until the error, the mean squared distance from the true average, falls below 10−9 (or 10−4). Every number is an average of 100 restarts. Failed peers return in the next round. The four methods are All-Reduce (restarting after a failure), Gossip, PushSum (a gossip variant) and averaging in random groups. Moshpit and random groups both use groups of 32, which is M = 32 and d = 2.

Read Table 4

Pick a swarm size, a failure rate and an error target. Bars show how many averaging rounds each method needed. Shorter is better.

Every value is copied from the paper’s Table 4 (Appendix I). A bar at 50 means the method had not reached the target within the 50 rounds the table allows, so its true number is higher.

Read the pattern. With no failures, plain all-reduce wins with 1 round at every size. Add failures, and it collapses: at N = 1,024 and p = 0.005 it needs 42.6 rounds, and at p = 0.01 it hits the 50-round limit. Gossip never reaches 10−9 in 50 rounds, and PushSum needs 49.0 at N = 1,024. Moshpit at N = 1,024 needs 2.0 rounds with no failures and only 5.9 at p = 0.01.

Two details are honest limits. At N = 512, which fills only half of a 32 by 32 grid, random groups beat Moshpit (6.1 against 8.2 with no failures). Without a full grid, the group sizes are uneven, and some groups can hold a single peer. And M = 32 was best in the paper’s million-peer study only at failure rate 0.001. Grid shape is a tuning choice. Using a proper 8×8×8 grid for 512 peers did converge faster than 32 by 32.

Test two: ResNet-50 on ImageNet (Section 4.2, Figure 4)

The task: train ResNet-50 on ImageNet to 75% top-1 accuracy, with batch size 256 and Nesterov SGD. Two fleets. Homogeneous: 16 servers with one V100 each. Heterogeneous: 81 GPUs in 64 servers and workstations, in two data centres and one office within 300 km. All links are 1 Gb/s Ethernet, with 1 to 6 ms latency, plus extra delay injected at the start of each round, drawn from an exponential distribution with a mean of 100 ms, to mimic shared use. Moshpit used a two-dimensional grid with 4 groups (homogeneous) and 8 groups (heterogeneous).

Rivals: All-Reduce SGD (only on the homogeneous fleet), AD-PSGD (gossip with 2 neighbours, compute and communication overlapped), and SGP (a gossip method with an exponential graph). The text reports: Moshpit and SGP are the two best. On the homogeneous fleet Moshpit is only slightly ahead of SGP. On the heterogeneous fleet its lead is over 30%. All-Reduce SGD has the best accuracy per epoch but the longest training time, 1.5 times Moshpit’s, because each step waits on the network. AD-PSGD has the best throughput but reached lower accuracy even after 150 epochs. The abstract summarizes this as 1.3 times faster than competitive gossip methods.

Test three: ALBERT-large on vanishing machines (Section 4.3)

Chapter 7 gave the details: 66 preemptible GPUs against one 8×V100 server, an iteration of 10 to 22 s against 25 s, the same final loss, and a 1.5 times faster run. It is the only test where machines truly came and went, which is why it matters most for the compute-islands story.

Where it falls short

In Table 4 at N = 1,024 and p = 0.005, which method reaches error 10−9 in the fewest rounds, and what is its count?

Chapter 9

The Field Guide

Review the numbers, the terms, the code and where to go next

You can now explain the paper from memory. Data-parallel training needs an average of gradients. Whole-swarm all-reduce is cheap but breaks when any peer fails. Gossip survives failures but is slow. Moshpit All-Reduce puts peers on a virtual grid, averages along one axis per round in small groups, and reaches the exact average in d rounds on a full grid. A DHT and a leader rule form the groups without a server. Moshpit SGD adds local steps, bandwidth-aware slicing, a pooled batch, and pseudo-gradients for optimizer memory.

The numbers that matter

WhatNumberWhy it matters
Butterfly all-reduce costs(N−1)/N per worker per moveDoes not grow with the swarm
Survival of one round, p = 0.0051,024 peers: 0.6%; a group of 32: 85%Small groups mostly succeed (derived, Ch 0)
Full gridMd peers, exact average in d rounds; 32 × 32 = 1,024 in 2Theorem C.1
Shrink factor per round(r−1)/N + r/N² = 0.0303 at N = 1,024, r = 32Equation 5, no graph dependence
Table 4, N = 1,024, p = 0.005, error < 10−9All-reduce 42.6, gossip 50+, PushSum 49.5, random groups 6.7, Moshpit 5.4 roundsMoshpit is the fewest with failures
Matchmaking timeunder 1 s (64 peers, one region), 2.9 s (two regions), up to 9 s (worldwide)Started 15 s early, ready in at least 95% of rounds
ImageNet, ResNet-50 to 75%81 GPUs, 64 servers, 1 Gb/s; lead over 30% vs the best gossip; abstract: 1.3×Heterogeneous fleet
ALBERT-large, 66 preemptible GPUs10 to 22 s per step vs 25 s; 1.5× faster; same final lossMachines truly vanished
Rent, ALBERT fleet vs 8×V100up to $15.43/h vs $24.48/h, with almost 3× the raw computeCheap but unreliable
One 8×V100 serverabout 25% slower than all-reduce SGD (27% on average)The method is for bad networks

The terms, in one line each

TermPlain meaning
BandwidthHow many bits per second a link carries. The width of the pipe.
All-reducePeers pass pieces so that all end with the average. No server.
Parameter serverOne machine collects, averages and returns. Simple, but a bottleneck.
GossipEach peer averages with a few neighbours, round after round.
DHTA shared dictionary spread over all peers. Moshpit uses Kademlia.
Group keyThe tuple of recent chunk indices that says which group to meet in.
Leader and priorityThe earliest timestamp leads, and everyone shares the leader’s list.
Local SGD, τTrain alone for τ steps, then average.
Pseudo-gradientThe weight change from averaging, fed to the optimizer as if a gradient.
PreemptibleCheap rented machines the provider may take back at any time.

A checklist for using the idea

  1. Is the network the problem? If all peers share a fast, reliable fabric, use plain all-reduce.
  2. Pick the grid. Choose M and d so that Md is near the swarm size and groups stay small. Avoid a half-empty grid.
  3. Pick τ. Raise it until drift hurts, then back off. Count rounds, not steps.
  4. Size slices by bandwidth. Give slow peers little or none of the averaging work.
  5. Hide matchmaking. Start it early, in the background.
  6. Handle joiners. Make newcomers download weights, optimizer state and schedule.
  7. Check the optimizer. If it keeps memory, feed it pseudo-gradients after averaging.

The core, as code

A small NumPy version of Algorithms 1 and 2 on a full grid, plus the hand solution of Chapter 6. It leaves out the DHT and the network.

pythonimport numpy as np

def moshpit_average(theta, M, d, rounds, p, rng):          # theta: [N, n], one row per peer, N = M**d
    N = theta.shape[0]
    for t in range(rounds):
        stride = M ** (t % d)                              # the grid axis used this round
        alive = rng.random(N) >= p
        for base in range(N):
            if (base // stride) % M != 0: continue       # start only at the first member of a group
            group = [base + k * stride for k in range(M)]
            if alive[group].all():                    # a group skips its round if any member failed
                theta[group] = theta[group].mean(axis=0)
    return theta

def moshpit_sgd(theta, grad_fn, gamma, tau, steps, M, d, p, rng):
    for k in range(steps):
        theta = theta - gamma * grad_fn(theta)             # local step on every peer: [N, n]
        if (k + 1) % tau == 0:                         # every tau steps, d group rounds
            theta = moshpit_average(theta, M, d, d, p, rng)
    return theta

def balanced_shares(b):                                  # b: bandwidth of each of M peers
    M = len(b)
    xi = max(1 / min(b), (2 * M - 2) / sum(b))            # best group time, in vector/bandwidth units
    cap = [max(0, (xi * x - 1) / (M - 2)) for x in b]     # most each peer may take
    return xi, [c / sum(cap) for c in cap]

Where this sits

Moshpit sits between two families. From the all-reduce family it takes cheap, exact averaging inside a group. From the gossip family it takes fault tolerance and no central server. Earlier gossip methods, such as decentralized parallel SGD, pay with graph-dependent convergence. Local steps come from parallelized SGD and federated averaging.

The Core Automation post lists Moshpit SGD in its history of low-communication training and later runs eight cells that trade fragments in pairs over three rounds, so that every cell’s update reaches all eight without an all-reduce. That pattern has the same shape as a Moshpit grid with M = 2 and d = 3. The post also stresses that slow links should deliver late and that nobody should wait. Moshpit’s group rule is one answer to that wish, and the lesson on heterogeneous and unreliable compute places it in the bigger picture.

Keep going

The takeaway. Do not ask everyone to succeed at once. Average in small groups that change every round, find them with a shared phone book and a first-come leader, and let the grid carry the answer to everybody.

Credit: this lesson re-teaches “Moshpit SGD: Communication-Efficient Decentralized Training on Heterogeneous Unreliable Devices” by Max Ryabinin, Eduard Gorbunov, Vsevolod Plokhotnyuk and Gennady Pekhimenko (NeurIPS 2021), arXiv 2103.03239, with code at yandex-research/moshpit-sgd. It was written for the series built around Rohan Anil’s post The Hitchhiker’s Guide to Training on Compute Islands (Core Automation, 2 November 2026). Our devices are toys unless the fine print says they use the paper’s numbers.

Your 512 peers sit on a fast, reliable switch with no failures, and you want the quickest average. What does the paper’s own evidence say?

Now explain the paper aloud, from memory: why one big all-reduce stalls, how a grid of small groups gets the exact average in d rounds, how peers find their group, what the shrink factor says, and what you give up on a single server. Then go back to the failing swarm at the top, set the failure rate to 1% and 1,024 peers, and say why Moshpit still converges.

Moshpit SGD: Communication-Efficient Decentralized Training on Heterogeneous Unreliable Devices
Read the paper · Authors’ code · The Core Automation post · Background lesson