Fused multiply-add in Go: the same float bits on amd64 and arm64

· gravitton/geometry

The cross product of a vector with itself is zero. Not approximately: x*y - y*x subtracts a number from itself. Run it on an Apple Silicon Mac:

x, y := 13.5, 1.9
x*y - y*x // -2.220446049250313e-16

Out of a million vectors crossed with themselves on an Apple M3, x*y - y*x is not zero for 998 919. On an amd64 server the same code prints zero every time. A geometry library that writes its products this way gives different answers on a developer’s laptop and on the machine running the game server, which is the one thing a game cannot have: a replay that diverges, a lockstep match that desyncs, a test that passes on CI and fails on a Mac.

The previous post made an answer independent of how it is asked. This one, the third of the shared rules, makes it independent of where.

Why the order of rounding changes

The Go specification allows this, in one sentence most of us never read:

An implementation may combine multiple floating-point operations into a single fused operation, possibly across statements, and produce a result that differs from the value obtained by executing and rounding the instructions individually.

A fused multiply-add computes x*y + z with one rounding at the end instead of one after the product and one after the sum. On arm64 the Go compiler emits one for this pattern. In x*y - y*x one product goes into the instruction exact and the other is rounded first, so the two products are no longer the same number, and their difference is the rounding error of one of them.

amd64 fuses too, when the binary is built with GOAMD64=v3. Compiled for it, the line a + (b-a)*t becomes a single VFMADD231SD. The default, v1, has no such instruction, so most servers and CI runners never see it.

The same sentence of the specification gives the fix:

An explicit floating-point type conversion rounds to the precision of the target type, preventing fusion that would discard that rounding.

float64(x*y) - float64(y*x) // 0 on every architecture

The conversion looks like a no-op, a float64 converted to float64, and that is exactly why it reads as a mistake to the next person editing the code. It is the only portable way to say “round here”.

Across statements

“Possibly across statements” is not a figure of speech. Writing the test for this post, I compared the library’s interpolation against my own, with inputs drawn from a random generator:

a, b, t := random.Float64()*1000, random.Float64()*1000, random.Float64()
geom.Lerp(a, b, t) != a + float64((b-a)*t)

The comparison failed one time in five, against a library that rounds every product. The compiler had fused the multiplication that produced b into the subtraction b-a on the next line, so the b in my expression was never rounded, and the b passed to Lerp was. Rounding the inputs, float64(random.Float64()*1000), made the two agree. Every product feeding a sum has to be wrapped, including the ones in the statement before.

What it breaks in a geometry library

The cross product is the side-of-line test. Every point-in-polygon test, every segment crossing and every winding order rests on its sign, so a sign that depends on the CPU is a collision that depends on the CPU. Interpolation is the other place it shows: an animation, a camera, a path followed with Lerp lands on a different point.

Until v1.15, gravitton/geometry wrote Lerp the way everyone writes it:

return a + (b-a)*t

On an M3, that expression differs from today’s rounded geom.Lerp in 136 634 of a million calls:

// lerp(848.0157632475306, 168.28576753700364, 0.8943908746796574)
a + (b-a)*t // 240.0714578379926
geom.Lerp   // 240.07145783799263

One ulp, in one call out of seven. Version 1.15 wrapped every product that feeds a sum in the library, Lerp, squared distances, matrix products, the circle intersections, and the changelog says it in one line: every product is rounded before it is added, so arm64 and amd64 v3 no longer fuse it into a multiply-add.

Keeping it fixed

A rule nobody can see erodes. The next contributor writes x*x + y*y, the tests pass on their machine, and the bits drift again. So the rule is checked, not remembered.

The shared CI workflow compiles every package twice, for arm64 and for amd64 v3, with -gcflags=-S, and keeps every fused instruction that lands in the library’s own functions:

GOARCH=$1 GOAMD64=$2 go test -c -o /dev/null -gcflags=-S "$pkg" 2>&1 \
  | awk '/[ \t](FN?M(ADD|SUB)[DS]|VFN?M(ADD|SUB)[0-9]+S[DS])[ \t]/ { ... }'

The list of source lines is diffed against .github/fused.txt, a short file of the fusions that are harmless, such as a halving or a sum of integers, keyed by the source text so it survives edits elsewhere in the file. A pull request that adds one fused line fails the build, and the line it names is the one to wrap. The step lives in the shared workflow, so every library gets it.

What it does not cover

math.Sincos(1e6)               // -0.34999350217129294, 0.93675212753314474
geom.Vec(1, 0).Rotate(1e6)     // 0.93675212753314474, -0.34999350217129294

The library can round its own products. It cannot round inside math.Sincos, which is compiled under the same specification as everything else. So the package documentation makes the promise with its one exception: the same inputs give the same bits on every architecture, except where the math package computes them, and a point placed from an angle, by Rotate or the vertices of a RegularPolygon, can differ in the last bit. A game that needs bit-identical rotation across machines rotates by a lookup table or by integer steps, which is what Turn on a direction does.

What it costs

Nothing measurable. On the M3, the plain expression and the rounded one:

ns/op
a + (b-a)*t, fused1.88
geom.Lerp, rounded1.93

The fused version saves one instruction, and one instruction is not what a 2D game is waiting for.

Same inputs, same bits

Same inputs, same bits, on the machines a game ships to, with the one exception stated where a caller looks. It is the other half of the rule from closed boundaries: an answer should not depend on how you ask the question, or on where.

Floating point is not the only way a game’s answer comes to depend on the run. A Go map walks its keys in a different order every time it is ranged, which is why the cells a query returns come as a sorted set, in the post on regions.

Every number above comes from the code of this post, pinned to geometry v1.20.1 and run on an Apple M3 with Go 1.27.4. CI runs it on amd64, where the first count is zero.