QSGD

Eight GPUs must tell each other 62 million numbers after every step, and the cable between them is slow. QSGD rounds each number up or down at random, so the average stays true while the message shrinks 8 times.

Learn how a gradient survives being squeezed to a few bits, why the rounding must be random, and what that bought on real networks.

Pick a bit width, then press Quantize again a few times. Each draw is wrong in a different way. Then press Average 1,000 draws and watch the errors cancel. After that we build, piece by piece, the rounding, the variance bill, the code that packs the bits, and the training results.

You need to know that a gradient is a list of numbers that says which way to move and a little algebra. We build the rest from zero.

Paper: QSGD: Communication-Efficient SGD via Gradient Quantization and Encoding, by Dan Alistarh, Demjan Grubic, Jerry Z. Li, Ryota Tomioka and Milan Vojnovic (NIPS 2017, arXiv 1610.02132). Read here as one of the papers behind the Core Automation post The Hitchhiker’s Guide to Training on Compute Islands (Rohan Anil, 2 November 2026). The background lesson is Communication Compression. Every idea is re-taught here in our own words and devices.

Squeeze a gradient

Toy gradient: 24 made-up numbers, the same on every visit. The quantizer is the paper’s Qs (Equation 4) with s = 2bits levels, as in the paper’s variance example for 4 bits. The draws are real random draws in your browser. The variance bound shown is the paper’s Lemma 3.1 for these 24 numbers.

Chapter 0

The Wire Is the Bottleneck

Count the bits one training step must move, and see why shrinking them is worth a paper

Picture eight GPUs training an image network together. Each GPU reads its own slice of the data. Each finishes its share of the arithmetic in a blink. Then all eight stop and wait, because every one of them must hear what the other seven learned before the next step can start.

What they trade is a gradient. A gradient is a list of numbers, one for every parameter (every adjustable number inside the network). Each number says: nudge this parameter up a little, or down a little, to make the mistakes smaller. A worker is one machine or one GPU in the team. Each worker computes a gradient on its own slice of data. The team averages the eight gradients and every worker takes the same step.

This recipe is synchronous data-parallel SGD. SGD stands for stochastic gradient descent: take a step downhill using a gradient computed from a small random batch of data. “Data-parallel” means every worker holds a full copy of the network and a different slice of the data. “Synchronous” means all workers finish a step together. The average is what makes the team as good as one worker with a batch eight times larger.

How big is the message?

The gradient has one number for every parameter. The paper’s Table 1 lists AlexNet, an image network, at 62 million parameters. Each number is stored in 32 bits (a bit is one 0 or 1). So one gradient is 62 million × 32 = 1.98 billion bits, which is 248 megabytes, since 8 bits make a byte.

How long does it take to move 248 megabytes? That depends on the link. Bandwidth is how many bits a link carries each second. It is written in Gbps, billions of bits per second. The Core Automation post describes a training run over a 25 Gbps link between two far-apart clusters. At 25 Gbps, 1.98 billion bits take 79 milliseconds. That is the cost of sending the gradient once, in one direction, and the team must do it every step.

Now shrink each number to 4 bits. The message becomes 248 million bits: 31 megabytes, and 9.9 milliseconds on the same link. Nothing else changed. Try it below.

Time the message

Each bar is the time to send one gradient of 62 million numbers at that bit width. Drag the link speed and watch all four bars scale together. The chosen bit width is bright.

25 Gbps

The 62 million count is AlexNet in the paper’s Table 1. The 25 Gbps default is the link in the Core Automation post. The time is size divided by bandwidth, with no waiting, no scale numbers and no coding overhead, so it is a lower bound. Real links are shared and slower.

What the paper measured

The authors timed real runs on Amazon machines with 16 GPUs (NVIDIA K80 cards). Their Figure 2 splits each epoch (one pass over the data) into compute time and communication time. Adding GPUs shrinks the compute time per GPU, so communication takes a larger share. For AlexNet on 16 GPUs with a batch of 1,024, more than 80% of training time went to communication. For a speech network called an LSTM on 2 GPUs, the share was 71%.

So the wire, not the arithmetic, decides how fast the team can go. Two fixes are possible. Send the message less often, which is the road of the local SGD lesson. Or send a smaller message every time. This paper takes the second road.

Why a smaller message is not free

The obvious move is to round every number to fewer bits. People did that. The 2014 method 1BitSGD keeps only the sign of each number (plus and minus), scales it by the average size, and keeps the rounding error at home to add into the next step. It worked well on speech networks. But the QSGD authors point out that nobody knew whether it must converge, even on easy problems, and whether more shrinking was possible.

QSGD offers a dial. You choose how many bits each number gets. Fewer bits mean a smaller message and a noisier gradient. The paper proves how much noise, and shows the trade is inherent: beating it by much would break a known lower bound on how many bits machines need to share to estimate an average. At the dense end, a message of about 2.8 bits per number (instead of 32) makes the gradient at most twice as noisy, so the team needs at most twice as many steps. Twice the steps for an 11 times smaller message is a net saving of about 5.7 times.

The Core Automation post lists the paper in its timeline as “Gradient quantization with convergence guarantees”. That phrase is the whole contribution. The Communication Compression lesson teaches the family of ideas around it. This lesson teaches the QSGD paper itself, to the level where you could write it.

The road

  1. Parallel SGD and its message: Algorithm 1, and where encode and decode plug in.
  2. Why plain rounding fails: bias, and why the average of many rounded numbers lies.
  3. Stochastic quantization: Equation 4, derived and worked on three numbers.
  4. The variance bill: Lemma 3.1, the trade-off, and what it costs in steps.
  5. Packing the bits: Elias coding and the 2.8n + 32 bound.
  6. Buckets, max and bits: how the experiments differ from the theory.
  7. What the experiments show: Table 1, Figure 2 and the accuracy results.
  8. Break it: train a tiny model with full precision, QSGD and plain rounding.
  9. Field guide: numbers, checklist, code, and where it sits.
One gradient has 62 million numbers at 32 bits each. About how long does one copy take to cross a 25 Gbps link, ignoring all overhead?

Chapter 1

Parallel SGD and Its Message

Walk one synchronous step of Algorithm 1 and find the two places where a compressor can plug in

Four friends stand on a foggy hillside. They want to walk to the valley floor, but nobody can see it. Each friend can feel the slope under their own feet and nothing else. If each walks by their own reading, they scatter. If they shout their readings to each other, average them, and all take the same step, they stay together and go down faster.

That is data-parallel SGD. Let us name the parts. The parameter vector x is the list of n numbers that define the network (n = 62 million for AlexNet). The loss f(x) measures how wrong the network is, and we want to push it down. The gradient ∇f(x) points uphill, so we step the other way.

Nobody can afford the exact gradient, which needs the whole dataset. Instead each worker draws a small random batch and computes a stochastic gradient, written g̃(x). It is a noisy copy of the truth, right on average: the paper writes E[g̃(x)] = ∇f(x), where E means “the average over all the random batches you might have drawn”. One step of plain SGD is the paper’s Equation 1.

xt+1
The parameter vector after the step. It is a list of n numbers, for example 62 million for AlexNet.
xt
The parameter vector now, at step t.
ηt
The step size (also called the learning rate): how far to walk. A small positive number you choose.
g̃(xt)
The stochastic gradient at xt: n numbers, noisy but right on average.

Algorithm 1, one step at a time

Now give the step to K workers. The paper’s Algorithm 1 is the same for every worker. Every worker starts the step holding the same x.

  1. Compute. Draw a fresh batch from this worker’s own data and compute g̃i, a list of n floating-point numbers.
  2. Encode. Turn g̃i into a message Mi, a string of bits. Plain parallel SGD does nothing here.
  3. Broadcast. Send Mi to every other worker.
  4. Decode. Turn each message you received back into n numbers, written ĝℓ. For plain SGD this recovers g̃ exactly. For QSGD it recovers a close copy.
  5. Update. Average the K decoded gradients and step: xt+1 = xt − (ηt/K) Σ ĝℓ.

Because every worker decodes the same K messages, every worker computes the same new x. The copies never drift apart. Steps 2 and 4, Encode and Decode, are the only lines the paper changes. All of QSGD lives in those two functions.

Why averaging helps: a worked step

Take a one-number problem to see the arithmetic. Let f(x) = x²/2, so the true gradient at x = 2 is exactly 2. Four workers draw different batches and get the noisy readings 1.5, 2.6, 2.1 and 1.9. Their average is (1.5 + 2.6 + 2.1 + 1.9) / 4 = 2.025. With η = 0.1 the step lands at x = 2 − 0.1 × 2.025 = 1.7975.

One worker alone might have used 2.6 and landed at 1.74, or used 1.5 and landed at 1.85. The average of four sits much closer to the truth. The rule is exact: if one gradient has variance σ² (its typical squared distance from the truth), the average of m independent ones has variance σ²/m. Four workers give a quarter of the noise.

The paper calls this minibatching: parallel SGD on K workers is the same as one SGD with a batch K times larger. Its Corollary 2.2 states the price in steps: the number of steps T needed to reach error ε is proportional to 2B/(Kε²), where B is the second moment bound, a cap on E[‖g̃‖²] (the average squared length of the gradient). Two things follow. More workers K means fewer steps. And more gradient noise B means proportionally more steps. Hold on to the second one. It is how the paper prices compression in Chapter 4.

What the message looks like on the wire

Count the data flow. The vector x has shape (n,). Each g̃i has shape (n,) in 32-bit floats, so Mi is n × 32 bits for plain SGD. Each worker sends it to the other K − 1 workers, so each worker also receives K − 1 messages. In this model each worker must take in (K − 1) × n × 32 bits every step.

Real libraries use smarter patterns than this all-to-all broadcast. An all-reduce (the data-parallel and all-reduce lesson builds one) cuts the traffic per worker to about twice the gradient size. The paper’s model is simpler and its message-size results carry over: whatever pattern moves the bytes, fewer bits per number means proportionally fewer bytes. The step also assumes every worker finishes together, which is what “synchronous” means. Run it below.

Run one synchronous step

Each dot is a worker. Press Run a step and watch the five stages light in order. Drag the worker count and the bit width to change the bytes each worker must take in.

8

The all-to-all broadcast is the model in the paper’s Algorithm 1. The 62 million count is AlexNet (Table 1). Message size is n × bits with no scale numbers or coding overhead, so the 4-bit figure is a floor. The animation is schematic, not a timing.

In Algorithm 1, which lines does QSGD change?

Chapter 2

Why Plain Rounding Fails

Learn the difference between noise that averages away and a lean that never does

A hundred workers are training together. In one coordinate of the gradient, the true value is small: 0.3 of one rounding step. Every worker sees about that value. To save bits, every worker rounds it to the nearest whole step. And 0.3 rounds to 0. All hundred workers send 0. The average is 0.

The team never moves in that coordinate. It does not matter how many workers join, or how long they train. A thousand workers all sending 0 still average to 0, and the truth is 0.3. This is the failure the paper wants us to avoid, and it has a name.

Noise and bias are different things

Any guess at a number has two kinds of error. Noise is the part that changes from guess to guess. If you average many guesses, noise shrinks, because up errors and down errors cancel. Bias is the part that is the same every time. Averaging does nothing to it. Formally, the bias of a guess is E[guess] − truth, the long-run average guess minus the right answer. A guess with zero bias is unbiased.

Round to nearest is deterministic: the same input always gives the same output, so its error is pure bias. Here is the error for a value that sits t of the way between two levels, with t from 0 to 1.

error
The rounded value minus the true value, measured in rounding steps.
0 − t
Below the halfway point the value rounds down to the lower level, which sits at 0. The estimate is too low by t.
1 − t
Above halfway the value rounds up to the next level, at 1. The estimate is too high by 1 − t.

For t = 0.3 the error is −0.3 on every worker, every step. That is 30% of a step lost, always in the same direction.

The fix: round at random, with the right odds

Suppose each worker flips a weighted coin. It rounds up to 1 with probability t and down to 0 with probability 1 − t. A single worker is now often wrong: with t = 0.3 it sends 1 three times in ten and 0 seven times in ten. But look at the long-run average.

E[estimate] = 0 × (1 − t) + 1 × t = t

The average is exactly the truth. The bias is zero. We paid for it with noise: each worker is wrong by a lot. The variance of one weighted coin is t(1 − t), which is 0.21 for t = 0.3, so one worker’s typical miss is √0.21 = 0.46 steps. That is larger than the 0.3 error of plain rounding!

So why is the coin better? Because noise averages away. The average of K workers has a typical miss of 0.46/√K. For K = 100 that is 0.046, a tenth of a step and shrinking. The 0.3 bias of plain rounding stays 0.3 for any K. Race them below.

Average many roundings

The horizontal axis is the number of workers, from 1 to 1,024. The vertical axis is how far the team’s average is from the truth. Drag the value between two levels, then drag the workers. Press Redraw for fresh coin flips.

0.30
64

Toy: one coordinate, every worker holding exactly the same true value t, measured in rounding steps. The random line uses 1,024 real coin flips in your browser; the team average at K workers is the mean of the first K flips. The flat line is exact. Illustrative, not from the paper.

Everything above used one coordinate. A real gradient has millions, and each one is rounded by its own independent coin. The average of a sum is the sum of the averages. So if every coordinate is unbiased, the whole gradient is unbiased, and the coins need no link to each other. This is why the method scales. The guarantee is built one coordinate at a time, and a gradient of 62 million numbers needs no new argument.

Where the paper sits

The authors list the earlier methods. Simply lowering the precision of each number was proved to converge by an earlier paper called Buckwild!, but only for convex problems (bowl-shaped, with one bottom) and sparse gradients. The method 1BitSGD sends only the sign of each number, scaled by the average size, and adds the rounding error back into the next step. It works in practice, but the authors state it is not known whether it gives any guarantee, even under strong assumptions.

QSGD takes the coin-flip idea and makes it a full design. A rounding that is unbiased turns compression into one clean thing: extra variance. The paper says it directly: “we view quantization as an independent source of variance for SGD, which allows us to employ standard convergence results.” The proofs for ordinary noisy gradients then apply, with a larger noise number. A concurrent paper, TernGrad, starts from a similar random rounding but limits every number to three values. The next chapter writes the coin-flip rule for any number of levels.

A coordinate's true value is 0.3 of a step. Why can adding more workers not rescue round-to-nearest?

Chapter 3

Stochastic Quantization

Build the paper’s quantizer Qs from a ruler and a weighted coin, and prove its average is exact

Take a ruler that runs from 0 to 1. Put s + 1 marks on it, evenly spaced, so that the gaps are 1/s wide. For s = 4 the marks sit at 0, 0.25, 0.5, 0.75 and 1. These marks are the quantization levels: the only values the message is allowed to carry. A number that lands between two marks must pick one of its two neighbours. The previous chapter showed how to pick: flip a coin weighted by how close the number is to each neighbour.

One thing is missing. Gradient numbers are not between 0 and 1. They can be 0.0003 or 40. So the quantizer first rescales the whole gradient to fit the ruler, and puts the scale back at the end. That is the whole design. Here are the steps for a gradient v with n numbers v1 to vn.

  1. Measure the length. The 2-norm ‖v‖2 is the ordinary length of the vector: the square root of the sum of the squares. It is one number.
  2. Normalize. For each coordinate compute ai = |vi| / ‖v‖2. No coordinate can be longer than the whole vector, so every ai lies between 0 and 1. It fits the ruler.
  3. Find the gap. Find the integer ℓ such that ai sits between ℓ/s and (ℓ+1)/s.
  4. Weigh the coin. The chance to go up is p = ai·s − ℓ, how far ai has walked through the gap.
  5. Flip. With probability p take the upper mark (ℓ+1)/s. Otherwise take the lower mark ℓ/s. Call the result ξi.
  6. Restore. Output ‖v‖2 × sign(vi) × ξi.

The paper packs these steps into Equation 4. The sign is split off first, because the ruler only holds sizes.

Qs(vi)
The quantized version of coordinate i, using s levels. It is a random number: two runs can differ.
‖v‖2
The length of the whole gradient. One 32-bit number is sent to carry it.
sgn(vi)
The sign: +1 if vi is zero or above, −1 if below. One bit per coordinate.
ξi(v, s)
The chosen mark, one of 0, 1/s, 2/s, up to 1. It equals ℓ/s with probability 1 − p, and (ℓ+1)/s with probability p.

Why the average is exact

Take the average over the coin. The lower mark carries weight 1 − p and the upper mark carries weight p.

E[ξi] = (1 − p)·ℓ/s + p·(ℓ+1)/s = ℓ/s + p/s = (ℓ + p)/s = (ℓ + ais − ℓ)/s = ai

The ℓ cancels and E[ξi] = ai = |vi|/‖v‖2. Multiply by the norm and the sign, and E[Qs(vi)] = vi. This is part (i) of the paper’s Lemma 3.1, unbiasedness. Therefore a quantized gradient is itself a valid stochastic gradient, and the standard SGD guarantees apply. The paper adds that among all ways to land on these marks with the right average, this coin has the smallest variance.

A worked example, every step

Let v = (3, −4, 12) and s = 4. The length is √(9 + 16 + 144) = √169 = 13. The three normalized sizes are 3/13 = 0.2308, 4/13 = 0.3077 and 12/13 = 0.9231. Multiply each by s = 4 to see where it lands on the ruler counted in gaps: 0.9231, 1.2308 and 3.6923.

Coordinatea = |v|/13a × 4ℓpSends (with chance)
v1 = 30.23080.923100.92310.25 (92.3%) or 0 (7.7%)
v2 = −40.30771.230810.23080.5 (23.1%) or 0.25 (76.9%)
v3 = 120.92313.692330.69231 (69.2%) or 0.75 (30.8%)

Check the first row against the formula. The upper mark 0.25 comes with chance 0.9231, so E[ξ1] = 0.25 × 0.9231 = 0.2308, which is a1. After restoring, 13 × 0.25 = 3.25 with chance 92.3% and 0 with chance 7.7% average to 3.0, the true v1. One possible draw sends the three marks (0.25, 0.25, 1) with signs (+, −, +). The receiver restores (3.25, −3.25, 13). It is off by (0.25, 0.75, 1), a squared error of 1.625 against ‖v‖2 = 169, under 1%.

What actually goes on the wire

The output of Qs is a tuple of three things, which the paper writes (‖v‖2, σ, ζ). The first is one 32-bit float. The second, σ, holds the n signs, one bit each. The third, ζ, holds n small integers ζi = s · ξi, each between 0 and s. In the example, ζ = (1, 1, 4). The receiver rebuilds each number as the norm × sign × ζi / s. Notice the shape of the data: n floats went in, and one float plus n signs plus n small integers came out. Chapter 5 shows how to pack them tightly.

The sparse end: s = 1

With s = 1 the ruler has only the marks 0 and 1. Every number in the message is then 0, +‖v‖ or −‖v‖. Coordinate i is nonzero with probability ai = |vi|/‖v‖2, so the expected number of nonzeros is the sum of the ai. A standard fact (the Cauchy-Schwarz inequality) says that n numbers whose squares add to 1 have absolute values that add to at most √n. So that sum is at most √n. A gradient with 62 million numbers sends, on average, fewer than 7,900 nonzeros: the gradient becomes sparse. This is part (iii) of Lemma 3.1: at most s(s + √n) nonzeros in expectation.

Probe one number below. Pick the number of marks, drag a, and flip.

Flip the weighted coin

The ruler holds the marks. The blue line is the true size a. The coin picks the mark below or the mark above. Flip once, or flip 500 times and watch the teal average settle on the blue line.

0.2308

The default a = 3/13 is the first coordinate of the worked example. The flips are real random draws in your browser. The lower and upper marks and the chance p are computed exactly from the paper’s definition of ξ.

In the worked example (v = (3, −4, 12), s = 4), how often does the second coordinate −4 get sent as the upper mark 0.5, which restores to −6.5?

Chapter 4

The Variance Bill

Derive Lemma 3.1, then turn extra noise into extra steps and see where the trade pays

Random rounding has no lean, but it is not free. Each coordinate lands on the wrong mark some of the time, and each miss is noise that the optimizer must put up with. A noisier gradient means more steps to reach the same loss. Compression buys a smaller message and sends the bill as extra steps. This chapter works out exactly how large the bill is.

We measure noise as variance: the average squared distance between the quantized gradient and the true one, E‖Qs(v) − v‖2. We compare it to the squared length ‖v‖2 of the gradient, so that 0.1 means “the noise is 10% as big as the signal”.

Deriving the bound

Work on one coordinate. Its two possible values sit a gap 1/s apart (before the ‖v‖ scale). A coin that goes up with chance p and down with chance 1 − p, over a gap of width 1/s, has variance p(1 − p)/s². This is the same variance formula as in Chapter 2, with the gap width 1/s multiplied in. Multiply by the squared scale ‖v‖2 and sum over coordinates.

E‖Qs(v) − v‖2
The expected squared distance between the quantized gradient and the true gradient: the variance, summed over all n coordinates.
‖v‖2
The squared length of the gradient. It sets the scale of every mark.
Σi pi(1 − pi)
The coin variances added up. Each pi is the chance of rounding up for coordinate i. Each term is at most 1/4.
s2
Twice as many gaps makes each gap half as wide, and the squared width a quarter.

Now bound the sum two ways. First, p(1 − p) ≤ p, and every p is at most 1. So the sum is at most n, and the variance is at most n‖v‖2/s². Second, p = ais − ℓ ≤ ais, since ℓ is not negative. So the sum is at most s Σ ai = s‖v‖1/‖v‖2. Here ‖v‖1 is the sum of the absolute values, and it is never more than √n ‖v‖2. So the sum is at most s√n, and the variance is at most √n‖v‖2/s. Both bounds hold, so the smaller one wins. This is Lemma 3.1 (ii).

E‖Qs(v) − v‖2 ≤ min( n/s² , √n/s ) · ‖v‖2

Read it as a dial. For few levels (s below √n) the second term is smaller and the noise falls like 1/s. Once s passes √n the first term takes over and the noise falls like 1/s². At s = √n both terms equal 1: the noise is at most as big as the signal, so the quantized gradient has second moment at most (1 + 1) = 2 times the original.

From noise to steps

Chapter 1 gave the rule: the steps needed grow in proportion to the second moment bound B. A quantized gradient has second moment at most (1 + min(n/s², √n/s)) times B. The paper’s Theorem 3.4 turns this into a convergence result for smooth convex problems, and Theorem 3.5 does the same for non-convex ones like neural networks (to a point where the gradient is small).

Now count the whole bill for the dense setting s = √n. The steps rise by at most a factor of 2. The message falls from 32n bits to at most 2.8n + 32 bits (Chapter 5 shows how), about 11 times smaller. Total communication is steps × bits per step, so the net saving is about 11.4 / 2 = 5.7 times. The paper states this saving as “≈ 5.7×”.

At the other end, s = 1 sends only about √n log n bits per step, a saving of thousands of times for a large network. But the bound lets the steps rise by up to a factor 1 + √n. For n = 62 million that is about 7,900 times more steps, which cancels the saving in the worst case. The dense end is where the theory makes a clear profit. The paper also proves the trade cannot be beaten: improving it for large n would break a known lower bound on the communication needed to estimate a mean across machines.

Try it. The device draws a random gradient with n numbers, quantizes it at each s many times, and measures the real variance.

Measure the variance bill

Both axes are logarithmic. The purple line is the paper’s bound. The warm dots are measured noise on a random gradient. The green tick marks s = √n. Drag s and change n.

16

The gradient is a seeded random vector of n Gaussian numbers, and each dot averages 40 quantizations. The bound is Lemma 3.1 (ii). Random Gaussian gradients are less spiky than real ones, so the dots sit below the bound. The bound is a worst case over all gradients.

At s = √n the quantized gradient has at most 2 times the second moment, and the message is about 11 times smaller. What is the net communication saving, according to the paper?

Chapter 5

Packing the Bits with Elias Codes

Spend few bits on the small integers that fill the message, and prove nothing is lost

After Chapter 3 the message holds a norm, n signs, and n small integers ζi between 0 and s. The obvious way to send an integer between 0 and s is a fixed width: log2(s + 1) bits each. With s = 255 that is 8 bits. It works, but it wastes bits, because the integers are not equally likely.

Look at the sizes. A coordinate’s integer is about s times its share of the gradient’s length, ai. With n numbers sharing a fixed total length, a typical ai is about 1/√n. At s = √n a typical integer is about 1. Zeros and ones dominate. Large integers like 30 exist only for the few big gradient numbers. The paper’s key remark is that “larger integers are less frequent”. A good code gives small integers short codewords and large integers long ones.

The Elias recursive code

A code here is a rule that turns each integer into a string of bits so that the receiver can read the stream back with no marks between numbers. Such a code is prefix-free: no codeword starts with another. The paper picks the recursive Elias code (also called the Elias omega code), invented in 1975. Its great virtue is that the receiver does not need to know in advance how large a number can be. Here is how to write Elias(k) for a positive integer k.

  1. Start with the string “0”. This final 0 will mean “stop”.
  2. Prepend the binary form of k. It begins with a 1.
  3. Recurse. Let k′ be the number of bits you just added, minus one. If k′ is more than 1, prepend the binary form of k′ and repeat. If k′ is 1 or less, stop.

Try k = 7. Start with “0”. Prepend 111 to get “1110”. Three bits were added, so k′ = 2. Prepend 10 to get “101110”. Two bits were added, so k′ = 1: stop. Elias(7) = 101110, six bits. A few more: Elias(1) = 0 (one bit), Elias(2) = 100, Elias(3) = 110, Elias(4) = 101000, Elias(8) = 1110000 (seven bits), Elias(16) = 10100100000 (eleven bits). The length grows like log k + log log k + … + 1, which the paper writes as (1 + o(1)) log k + 1.

Reading it back is a short loop. Set N = 1. Look at the next bit. If it is 0, stop: the answer is N. If it is 1, read that bit plus N more bits, take them as a binary number, make that the new N, and look at the next bit again. Decode 101110: N = 1; bit 1, so read “10” (the 1 plus one more bit): N = 2; bit 1, so read “111” (the 1 plus two more bits): N = 7; next bit 0: stop with 7. The decoder never needed an upper bound on k.

Two ways to use it

Sparse regime (few levels). When s is small, most integers are zero. Then do not send the zeros at all. Send the norm in 32 bits. Then, for each nonzero coordinate in order, send three things: the gap since the last nonzero coordinate as Elias(gap), one sign bit, and the integer as Elias(ζi). The receiver knows where the message ends, so it needs no end marker. Take a gradient with n = 8 and s = 4 whose integers are ζ = (0, 0, 2, 0, 0, 1, 0, 3), with signs −, +, + on the nonzero places. The stream is as follows.

[32-bit norm] 110 1 100 | 110 0 0 | 100 0 110  = 32 + 19 = 51 bits, against 8 × 32 = 256

The first nonzero sits at position 3, so Elias(3) = 110. Its sign is minus (1). Its value 2 is Elias(2) = 100. The next nonzero is 3 places on: Elias(3) = 110, plus sign (0), value 1 is Elias(1) = 0. The last is 2 places on: Elias(2) = 100, plus sign (0), value 3 is Elias(3) = 110. That is 19 bits for the content and about five times fewer than 256. For this regime Lemma 3.1 (iii) bounds the number of nonzeros by s(s + √n), and Theorem 3.2 turns it into a bit count.

Dense regime (s = √n). Here most integers are nonzero, and gaps would only cost bits. The paper switches to sending every coordinate: one sign bit plus Elias(ζi + 1). Adding 1 lets the zero be coded, as Elias(1), a single bit. So a zero costs 2 bits with its sign, a one costs 4, a two costs 4, a three costs 7. The paper proves that in expectation the total is at most 2.8n + 32 bits (Corollary 3.3). That is under 2.8 bits per number, against 32.

Where does 2.8 come from? The same computation as Chapter 4 shows that the squares of the integers add up to at most about 2n in expectation when s = √n, so the typical integer is small. The code length grows like log k, which curves flat, so a spread of values never costs more than a fair share of equal ones (Jensen’s inequality: for a curve that bends flat, the average of the lengths is at most the length of the average). The full proof is Lemma A.6 in the appendix.

One honest caveat. The proof counts each integer’s code as log k + 1 bits and hides the smaller log log k terms inside its (1 + o(1)) factor. The exact Elias code is a little longer. A perfectly flat gradient at s = √n has every integer equal to 1, which costs 4 bits per number with its sign, and a random Gaussian gradient averages about 3.3. So 2.8 is the paper’s analytic bound, and a real implementation lands near 3 to 4 bits per number. That is still about 8 to 10 times smaller than 32. Check it live below.

Pack and unpack a message

The bit string is the message. Colours: norm, gap, sign, value. Choose the textbook example, or a random 64-number gradient and drag s.

8

The textbook case is fixed at s = 4. The random modes draw a seeded Gaussian gradient and quantize it live with the paper’s Qs, then encode and decode with the Elias code above, and the check compares every decoded integer with the original. How a message ends is left to the transport, as in the paper’s bit count. The 2.8n + 32 bound is for s = √n and is the paper’s analytic bound; at other s it is only a reference.

Why does QSGD use a variable-length code instead of 8 fixed bits per integer?

Chapter 6

Buckets, Max and Bits in Practice

See how the experiments bend the theory, and read the cost of every bit width off one frontier

The theory in Chapters 3 and 4 treats the whole gradient as one vector with n numbers. For AlexNet that is n = 62 million. Plug that in. At s = 16 levels (4 bits) the bound is √n/s = 7,874 / 16 = 492. The noise could be 492 times the signal. A network cannot train through that.

The reason is the single scale number. One gradient number that is much larger than the rest sets ‖v‖2 for everybody. All the small numbers then squeeze into the first gap of the ruler, where they round to 0 or to one tiny mark. The paper’s remedy, in Section 4, is simple and is the version used in every experiment.

Cut the gradient into buckets

Lay the gradient out as one long list. Cut it into buckets of d numbers in a row: numbers 1 to d, then d + 1 to 2d, and so on. Quantize each bucket by itself, with its own scale number. The messages for all buckets travel together.

Every guarantee now depends on d, not n. Each bucket obeys Lemma 3.1 with d in place of n. Add the buckets up and the noise is still at most min(d/s², √d/s) times the squared length of the whole gradient. The paper’s own example: d = 512 and 4 bits (s = 16) gives √512 / 16 = 22.6 / 16 = 1.41. That is close to the s = √n dense setting, and about 350 times lower than the 492 above. This is the reason the experiments converge.

The price is one scale number per bucket, 32 bits, so 32/d extra bits per number. For d = 512 that is 0.0625 bits per number. Setting d = 1 means one number per bucket: the scale is the number itself and nothing is lost, so d = 1 is plain SGD. Setting d = n is the full theory. Bucket size is a second dial beside the bits.

Scale by the maximum

The second change: divide by the largest absolute value in the bucket, instead of the 2-norm. The largest number then sits exactly on the top mark (level 1) and the rest spread over the whole ruler. Fewer numbers fall in the first gap. The authors found it gives slightly higher accuracy for the same number of iterations. The cost is that the sparsity guarantee (Lemma 3.1 iii) no longer holds, though in practice they see plenty of zeros anyway. At the dense setting the theory used no sparsity, so the bounds are unaffected.

Put the two together to count the bits. A bucket of d numbers at b bits costs d·b + 32 bits (b bits per number, and one 32-bit scale). That is b + 32/d bits per number. The three settings of the paper’s timing study, with their compression against 32 bits, are below.

SettingBits per numberSmaller than 32-bitNoise bound min(d/s², √d/s)
2 bits, bucket 1282.2514.2 times2.83
4 bits, bucket 5124.067.9 times1.41
8 bits, bucket 5128.064.0 times0.0078

The paper says the 4-bit setting sends about 8 times less than 32-bit, matching the 7.9 above. It says 4-bit sends 77% more data than 2-bit. The formula gives 4.06 / 2.25 = 1.81, about 81% more. The gap is likely coding detail the paper does not spell out. I trust the paper’s measured number for its code, and the formula for the idea. One more caution: s = 2b levels plus a sign need a little more than b bits in a fixed-width field. The paper does not spell out how its 4-bit runs pack the values, so read b as the paper’s name for the setting, with variable-length coding doing the packing.

Other details that matter

Now explore the frontier. Each dot is one pair of bit width and bucket size. Left is a smaller message, down is less noise.

Choose bits and bucket

Pick a setting from the paper, or drag your own. The big dot is your choice; faint dots are every other pair. Good settings sit low and to the left.

4
512

Bits per number is b + 32/d (one 32-bit scale per bucket); levels are s = 2b, the paper’s convention in its 4-bit example. The noise bound is Lemma 3.1 with d in place of n. The paper reports that 4-bit with bucket 8192 loses 0.68% top-1 accuracy on AlexNet at equal epochs; the bound alone cannot tell you where a network breaks.

Why do the experiments quantize in buckets of 512 numbers rather than the whole 62-million-number gradient at once?

Chapter 7

What the Experiments Show

Read Table 1 and Figure 2 with one formula, and learn where the speedup comes from and where it stops

The theory says QSGD converges. The business question is different: does a smaller message save more time than the extra noise costs? The authors tested it on Amazon EC2 machines with 16 NVIDIA K80 GPUs that talk to each other directly (GPUDirect peer-to-peer; the machines did not support NVIDIA’s NCCL library). They built QSGD in Microsoft’s CNTK toolkit, with the Message Passing Interface (MPI) moving the bytes, and released the code.

The tasks were image classification on ImageNet (the ILSVRC 2015 photo set) and CIFAR-10 with AlexNet, VGG, ResNet and Inception networks, and speech recognition on the AN4 dataset with an LSTM (a network that reads sequences). Their rule was zero error tolerance: use the standard settings tuned for 32-bit, raise the batch size only when needed to balance communication and compute, and never past the point where accuracy drops.

Figure 2: the wire eats more as GPUs grow

Figure 2 splits each epoch into communication time (bottom of each bar) and compute time (top), for 2, 4, 8 and 16 GPUs, in 32-bit and 4-bit QSGD. Adding GPUs shrinks the compute each GPU does but not the gradient each must send, so the communication share grows. The authors sort the networks into communication-intensive (AlexNet, VGG, the LSTM) and computation-intensive (Inception, ResNet). For 32-bit AlexNet on 16 GPUs with batch 1,024, more than 80% of the time went to communication. For the LSTM on 2 GPUs with batch 256 it was 71%. Epoch time varied by less than 1% between runs, so the figure has no error bars.

One formula explains the speedup

Suppose communication takes a fraction f of the epoch, and QSGD makes the communication r times faster, compute unchanged. The new epoch time, as a fraction of the old, is the compute part (1 − f) plus the shrunken communication part f/r.

speedup
Old epoch time divided by new epoch time.
(1 − f)
The part of the epoch spent computing. QSGD does not change it.
f / r
The part spent communicating, now r times shorter. The paper counts the time spent compressing and decompressing as communication time.

Check it on the paper’s numbers. AlexNet on 16 GPUs: f is just over 0.8 and 4-bit QSGD cuts communication time r = 4 times. Then 1 / (0.2 + 0.8/4) = 1 / 0.4 = 2.5, and the paper reports the epoch time falling 2.5 times. The LSTM: f = 0.71 and r = 6.8 give 1 / (0.29 + 0.104) = 2.5, while the paper reports 2.7. The small gap is expected, because the 71% is rounded and the batch size shifts these ratios a little. The formula also shows a ceiling: even with free communication (r infinite) the speedup stops at 1 / (1 − f), which is 5 times for f = 0.8. Try other numbers.

Shrink the communication share

The top bar is one 32-bit epoch, split into compute and communication. The bottom bar is the same epoch with QSGD. Use the two paper cases as presets, or drag your own share and reduction.

80%
4.0x

The formula is exact for the model it states: compute unchanged, communication cut by r. The AlexNet and LSTM presets use the paper’s numbers (more than 80% and 71% communication in 32-bit; 4x and 6.8x less communication time). The third preset is illustrative. The paper reports measured epoch speedups of 2.5x and 2.7x.

Table 1: end-to-end results on 8 GPUs

Table 1 trains each network to full convergence on 8 GPUs and compares final accuracy and time. Top-1 accuracy is the share of images where the single best guess is right. Top-5 is the share where the right answer is among the five best guesses.

NetworkDataParamsTop-1, 32-bitTop-1, QSGDSpeedup, 8 GPUs
AlexNetImageNet62M59.50%60.05% (4 bit)2.05x
ResNet152ImageNet60M77.0%76.74% (8 bit)1.56x
ResNet50ImageNet25M74.68%74.76% (4 bit)1.26x
ResNet110CIFAR-101M93.86%94.19% (4 bit)1.10x
BN-InceptionImageNet11Mnot runnot run1.16x (projected)
VGG19ImageNet143Mnot runnot run2.25x (projected)
LSTMAN413M81.13%81.15% (4 bit)2x (2 GPUs)

Read the table in three passes. First, accuracy: four of the five trained networks end higher than 32-bit (AlexNet by 0.55 points) and ResNet152 ends 0.26 points lower, so the extra noise did little harm. The authors point to earlier work showing gradient noise can help training, and call quantization “a source of zero-mean noise, which happens to render communication more efficient”. Second, speedup tracks how communication-heavy the network is: the biggest gains are AlexNet and VGG19 (many parameters, little compute per parameter), and the smallest are the compute-heavy ResNet110 and Inception. Third, the ResNet152 gain grows with GPUs: 1.56 times on 8, and about 1.8 times on 16 according to the abstract. Two rows are projections, not runs.

Where it hurts

The authors also found limits. Across all their experiments 8 bits with a bucket of 512 always recovered or beat full precision. Pushed harder, accuracy falls. Four-bit QSGD with a bucket of 8,192 lost 0.57% top-5 and 0.68% top-1 on AlexNet at equal epochs. Two-bit QSGD with a bucket of 64 left a gap of 1.73% in the paper’s text. Convolutional layers were the most sensitive: 2 bits hurt them, while 4 or 8 bits recovered the accuracy. Recurrent networks tolerated the squeeze better. For the curves, Figure 3 plots test accuracy against time for AlexNet (marked “> 2x faster”), error against time for the LSTM, and test accuracy against epochs for ResNet50. I describe it from its caption; the paper’s figure carries the curves.

Communication is half of a 32-bit epoch, and QSGD cuts communication time by 4 times. What is the epoch speedup?

Chapter 8

Break It: Train with Three Quantizers

Train a small model with full precision, QSGD and plain rounding, and watch bias stall one of them

You now hold every piece of the method. This chapter puts the pieces to work in one test you can run and break. A small model trains in your browser on eight simulated workers. Three runs share the same data and the same noise. One sends 32-bit gradients. One sends QSGD messages. One sends messages that round every number to the nearest level, the method Chapter 2 warned about.

The setup

The model has 32 parameters, and the loss is a simple bowl: loss = ½ Σ hi xi². The parameters start at 1 and the goal is 0. Two of the 32 parameters, the first of each bucket of 16, are outliers: they carry no loss but their gradients are drowned in big random noise (standard deviation 1). The other 30 parameters carry the real signal. Their curvature h is 0.1, so a parameter at x = 1 has gradient 0.1, and they carry a tiny noise of 0.005.

This is a toy of a common real pattern: one loud coordinate in a bucket sets the scale for all the quiet ones. Each step, every one of the 8 workers computes its noisy gradient. Each worker quantizes it in buckets of 16 with max scaling (Chapter 6). The 8 messages are decoded and averaged, and the step size is 0.3.

What do you expect? The loud coordinate sets the scale. In the first bucket its gradient is about 1, so with 2 bits (4 levels) the marks are 0.25 apart. A quiet gradient of 0.1 sits at 0.4 of one gap. Round to nearest sends 0 for it, at every step, from every worker. This is the Chapter 2 failure, now inside a real training loop.

Here is the data flow in the toy, step by step. The parameter vector x has shape (32,). Each of the 8 workers makes a gradient of shape (32,), splits it into 2 buckets of 16, and finds the maximum absolute value of each bucket. With s = 2bits levels, every number becomes an integer from 0 to s plus a sign, rounded by the rule under test. The decoded gradients are averaged over the 8 workers, and x moves by 0.3 times that average. No network is involved: the point is the arithmetic of the message, not its speed.

Race three quantizers

Each line is the loss over 400 steps on a log scale; lower is better. Choose the bits. Press Train again for new noise. Watch what happens to the red line at 2 bits, then at 8.

Toy run, computed live: 32 parameters in 2 buckets of 16, 8 workers, 400 steps, step size 0.3, max scaling with s = 2bits levels, as in the paper’s practical variant. QSGD rounds up with the weighted coin; the other rounds to the nearest level. Illustrative, not from the paper. The seed changes every time you press Train again.

Symptom, measurement, fix

Symptom. At 2 bits the round-to-nearest loss falls for a while and then flattens, thousands of times above the full-precision line. Giving it more steps does not help, because it has stopped moving on the quiet parameters. QSGD keeps falling with it.

Measurement. The median over 9 seeds at step 400, from my runs of this exact toy, shows the gap. Full precision ends at about 6e-6. At 2 bits QSGD ends near 2.4e-4 and round-to-nearest near 1.1e-2, about 47 times worse than QSGD. At 4 bits the numbers are 5.5e-5 and 1.3e-4, a factor of 2.3. At 8 bits all three end between 6.3e-6 and 6.7e-6. So bias hurts when the grid is coarse compared with the signal, and it vanishes when the grid is fine.

Fix. Replace the rounding with the weighted coin. The quiet gradient of 0.1 now goes to the 0.25 mark about 40% of the time and to 0 the rest, and the average over workers and steps is correct. Look also at what the fix costs. The QSGD line sits above full precision: at 2 bits its floor is about 38 times higher, and at 4 bits about 9 times. That is the variance bill of Chapter 4, and it is why the authors keep 4 or 8 bits for real networks.

What the paper does not claim

The Core Automation post, which lists QSGD in its timeline as “Gradient quantization with convergence guarantees”, is about training across slow links. There, as in the post’s own account of Streaming DiLoCo, quantization is one of several tools: it appears alongside sending fewer parameters and sending them less often. The post’s own two-site run compressed the exchanged values with stochastic rounding plus error feedback: the same coin as this chapter, with a memory of past rounding error added.

At 2 bits, QSGD ends with a higher loss than full precision but far lower than round-to-nearest. What explains both gaps?

Chapter 9

Field Guide

Keep the numbers, the checklist and the core code, and see where QSGD sits among its neighbours

In one paragraph. Workers in synchronous data-parallel SGD swap gradients every step, and on a slow link the swap dominates the time. QSGD shrinks the message by rounding each gradient number, scaled by the length of its bucket, to one of s evenly spaced levels, up or down by a weighted coin. The coin makes the result unbiased, so the standard SGD guarantees still hold with a larger variance of at most min(n/s², √n/s) times the squared gradient length. An Elias code then packs the small integers. At s = √n the paper proves a message of at most 2.8n + 32 bits and at most twice the steps, a net saving of about 5.7 times. In practice, buckets and max scaling at 4 to 8 bits kept accuracy and gave end-to-end speedups of 1.1 to 2.25 times on a single multi-GPU machine.

The numbers, with their source

QuantityValueWhere
QuantizerQs(vi) = ‖v‖2 · sgn(vi) · ξi, unbiasedEq. 4, Lemma 3.1 (i)
Noise boundmin(n/s², √n/s) · ‖v‖2Lemma 3.1 (ii)
Nonzerosat most s(s + √n) in expectationLemma 3.1 (iii)
Dense regimes = √n: at most 2.8n + 32 bits, noise at most 2xCorollary 3.3
Net saving32n vs 2.8n at up to 2x steps: about 5.7xIntroduction
Bucket exampled = 512, 4 bits: bound √512/24 = 1.41Section 4
Skip rulematrices under 10K numbers stay 32-bit; over 99% of parameters are quantizedSection 5, Protocol
16 GPUs, AlexNetover 80% communication; 4-bit cuts it 4x, epoch 2.5xSection 5, Figure 2
2 GPUs, LSTM71% communication; cut 6.8x, epoch 2.7xSection 5
8 GPUs, Table 1AlexNet 59.50% to 60.05%, 2.05x; ResNet152 77.0% to 76.74%, 1.56xTable 1
16 GPUs, ResNet152full accuracy 1.8x fasterAbstract
Too aggressive4-bit, bucket 8192, AlexNet: −0.57% top-5, −0.68% top-1Section 5, Accuracy

Terms in one line each

TermPlain meaning
GradientOne number per parameter, saying which way to nudge it.
WorkerOne GPU or machine in the team; it holds a full copy of the model.
Bandwidth, GbpsBits a link carries per second; Gbps is billions of bits per second.
Stochastic gradientA gradient from a random batch: noisy, right on average.
Bias, unbiasedA lean that is the same every time; unbiased means the long-run average is the truth.
VarianceThe average squared miss; noise that averaging shrinks.
Quantization level, sOne of s + 1 evenly spaced marks between 0 and 1 that a number may take.
BucketA run of d numbers quantized with its own scale.
Elias codeA variable-length code that gives small integers short bit strings.
All-reduceThe pattern that sums every worker's data and returns the result to all of them.
1BitSGDSends only signs, with the rounding error carried to the next step; no guarantee known.

Checklist before you compress a gradient

  1. Measure f first. Find the share of step time spent on communication. The speedup cannot beat 1 / (1 − f).
  2. Round at random. Use the weighted coin, never round to nearest, so the message is unbiased.
  3. Use buckets. Pick d near 512 and one scale per bucket. Do not use one scale for the whole model.
  4. Start at 8 bits. The paper found 8 bits with d = 512 always matched full accuracy. Go lower only while accuracy at equal epochs holds.
  5. Keep the learning rate. Shrink the bucket instead of changing it.
  6. Leave small tensors alone and hide quantization behind the next compute step.

The core as code

pythonimport numpy as np

def qsgd_quantize(g, bits=4, bucket=512, rng=np.random):
    """g: float32 (n,). Returns scale (B,1), sign (B,d), z (B,d) integers 0..s."""
    s = 2 ** bits                                      # number of gaps on the ruler
    pad = (-len(g)) % bucket
    x = np.pad(g, (0, pad)).reshape(-1, bucket)       # (B, d), B = ceil(n / d)
    scale = np.abs(x).max(axis=1, keepdims=True)     # max scaling: one float per bucket
    a = np.abs(x) / np.where(scale == 0, 1, scale) * s  # each entry in [0, s]
    low = np.floor(a)
    z = low + (rng.random(a.shape) < a - low)         # the weighted coin: up with chance a - low
    return scale, np.sign(x), z.astype(np.uint16), len(g)

def qsgd_dequantize(scale, sign, z, n, bits=4):
    return (scale * sign * z / 2 ** bits).reshape(-1)[:n]   # E[output] = g

def elias(k):                                        # recursive Elias code of an integer k >= 1
    code = "0"
    while k > 1:
        b = bin(k)[2:]; code = b + code; k = len(b) - 1
    return code

# one synchronous step on worker i (Algorithm 1)
g = grad(x, batch_i)                                  # (n,) float32
msg = encode(qsgd_quantize(g))                        # about n*b/8 + 4*n/d bytes
msgs = broadcast(msg)                                 # K messages, one per worker
g_hat = sum(qsgd_dequantize(*decode(m), len(g)) for m in msgs) / K
x = x - lr * g_hat

Where it sits

The Core Automation post places QSGD in a timeline of ideas for training across slow links: 1-bit SGD in 2014 (sign quantization with error feedback), QSGD in 2016 (“gradient quantization with convergence guarantees”), Deep Gradient Compression in 2017 (send only a small fraction of values, with momentum correction), and PowerSGD in 2019 (low-rank compression that works with all-reduce). QSGD is the member of the family that carries a proof. Its limits on a compute island are the ones in Chapter 8: it shrinks each message by up to about 8 times but still sends a message every step. The post’s other lever is to send less often, which the local SGD and DiLoCo lessons teach.

The paper also contains pieces this lesson only touches. QSVRG quantizes a variance-reduced variant of SGD and keeps its fast convergence: the gap to the optimum shrinks by 0.9 each epoch (Theorem 3.6). The paper notes that its full version applies QSGD to plain gradient descent by keeping only the largest components, and the abstract claims convergence under asynchrony. Theorem 3.5 covers non-convex objectives such as neural networks.

Keep going

The takeaway. Compressing a gradient is safe when the rounding is random with the right odds, because then it only adds noise, and noise averages out. Pay the noise bill with bits you choose, and measure the wire before you spend effort on it.

Open Teach and explain QSGD on a whiteboard, or flip through the Sparks cards. When you are ready, go back to the squeeze and ask what each bit width now costs you in noise.

Credit: QSGD was written by Dan Alistarh, Demjan Grubic, Jerry Z. Li, Ryota Tomioka and Milan Vojnovic and appeared at NIPS 2017 (arXiv 1610.02132). The Elias code is from Peter Elias, 1975. This lesson re-teaches the paper in new words and devices; every number marked as from the paper is theirs, and toy numbers are labelled. It is one of the papers behind The Hitchhiker’s Guide to Training on Compute Islands by Rohan Anil of Core Automation (2 November 2026).

A team on a 25 Gbps link finds communication is 30% of step time. What is the best speedup any gradient compressor could give them?
QSGD: Communication-Efficient SGD via Gradient Quantization and Encoding
Read the paper · Background: Communication Compression · Back to Gleams