FizzBuzz at the Frontier: With Lean, Humans Need Not Apply
llms verification performance lean
FizzBuzz, if you weren't familiar, is a classic children's playground game. The game is to count up from 1 and while counting, for each number, if divisible by 3, say Fizz instead, if divisible by 5, then Buzz, if by both, then FizzBuzz. For example, the start looks like:
Of course, it's pretty trivial to write a program that implements FizzBuzz yourself, but making it go fast? That's a little more difficult than it sounds, and involves some fun low-level systems hackery.
There's this classic 2021 blog post by Mark Litwintschik, "The Fastest FizzBuzz Implementation", where he walks through the implementation of the winner (at the time) of a 2020 Code Golf Stack Exchange competition to write the fastest FizzBuzz implementation.
This program is a marvel of engineering, and involved exploiting a
number of low-level systems tricks, from using AVX2 vector
instructions to compute hundreds of lines of FizzBuzz at once, to
using the vmsplice system call to optimise outputting bytes to the
receiving process. The winner was a Computer Science PhD student at
the University of Birmingham, with a star-studded resume. Quoting from
Mark's post:
The developer behind the Assembler version is Alex Smith, a doctoral researcher studying for a PhD in the School of Computer Science at the University of Birmingham in the UK. Alex is a reserve on the UK Olympic Maths Team and has a degree in electronic engineering.
Using his expert knowledge of systems architecture, Alex was able to obtain a FizzBuzz throughput of 60.8 GiB/s. Alex mentions in his original submission that he wasn't able to get multi-threading to help, but since then, a later submission in 2024 by David Frank incorporated an even more complex concurrent design that beat that even further and pushed the highest throughput up to a recorded count of 208.3 GiB/s (224 GB/s). For four years, this has remained the record.
I am pleased to tell you today, humans are no longer relevant to the problem of writing the fastest FizzBuzz implementations.
Compared to the reported frontier of human performance at 224 GB/s, running on the latest hardware, an LLM was able to build a hyper-optimised implementation that absolutely obliterates the human record and scales past the 300 GB/s wall:
Over the last few weeks, I had been asking a few LLM agents to implement and verify a hyper-optimised version of FizzBuzz entirely in assembly. Once the agents had a formally verified implementation, they could super-optimise, and iterate on the design and implementation to beat out the human record on every possible core count.
The final binary has:
- 1,053 lines of x86-64 assembly, written and tuned entirely by agents.
- One Lean theorem certifying every byte the binary prints, running on any configuration up to 64 threads.
- 334 GB/s on its slowest run, faster than the fastest recorded human run on the same machine.
The final numbers were obtained on the latest Ryzen 9 9950X (Zen 5,
Linux 7.0, mitigations off), taking the mean of 10 runs (the error
bars show the min and max throughputs). The human line is David's
program on the Ryzen 9 5950X from the competition, run with his pv -B
2M command and averaged over 5 runs. (Later in the blog post we also
dig into how the LLM and human versions fare on the older hardware
from the competition).
This blog post is about FizzBuzz, but the larger message is clear: you no longer need to be a genius systems hacker to be fast, even a joe-schmoe verification researcher like me can do it.
In the rest of this blog post, I'll walk you through the key results from this experiment:
- (1) a quick primer on using Lean for generating verified binaries, and how verification allows agents to super-optimise their binaries, then
- (2) the model of x86-64 and Linux that the agents built, a breakdown of the actual record-winning algorithm, and the specific theorem that was proven about it,
- and finally (3) the performance plots, for both programs on both machines and from 1 to 15 cores.
The source code is available here: https://github.com/kiranandcode/fastest-fizzbuzz
A Primer on Lean, Binary Verification and Superoptimisation
Lean is a theorem proving language that has been of some repute as of late, namely being used to close several open maths problems. Maybe most recently, it was instrumental in resolving the Riemann-Claude theorem:
The core idea of a theorem prover is providing a simple language in which users can write logical statements and mathematical proofs, and a small kernel will check that each step in the proof is a valid deductive step.
While Lean has had most impact so far in mathematics, there is a long history of using proof assistants for verification (including even in our very own blog: Bloom filters in Coq). It turns out you can use the same mechanised reasoning developed for mathematics just as well for reasoning about programs themselves.
For example, if we wanted to verify that a FizzBuzz algorithm produced FizzBuzz on the correct inputs:
def fizzbuzz (n : Nat) : String :=
if n % 15 = 0 then "FizzBuzz"
else if n % 3 = 0 then "Fizz"
else if n % 5 = 0 then "Buzz"
else toString ntheorem fizzbuzz_of_dvd_15
(n : Nat) (h : n % 15 = 0) :
fizzbuzz n = "FizzBuzz" := by
simp [fizzbuzz, h]This implementation of FizzBuzz here is cute and clean, but not quite a program we would want to run in the FizzBuzz competition: it is mostly just a mathematical model, and doesn't really talk about output at all.
Of course, we could easily wrap this program with a println (Lean is
also a programming language), but this would implicitly rely
on the Lean runtime (which has been known to have its own share of
bugs). More importantly, if we want to beat the hand-rolled
optimisations made by the system-hackers who set the human world
record, our implementation must necessarily reason about low-level
details such as AVX2 instructions, system calls or the actual pipe the
bytes get sent out in.
The answer is to not only reason about the mathematical model, but to also speak about the implementation's assembly instructions themselves. While this is usually a daunting task, requiring understanding of low level CPU details, thankfully, people have already been hard at work encoding a number of CPU instruction sets in Lean. The first ISA to take off in Lean was SAIL's RISC-V Model, which a cottage industry of verification projects now builds on, from MIT's verified xv6 kernel to our own verified interpreter, and the same RISC-V level was the target of Anthropic's OSS-Fuzz verification, albeit in Rocq. More recently, the Aeneas Rust verification team released their own semantics for x86-64 and AArch64, Kraken, developed as a joint project between the Lean FRO, Google and INRIA.
While people so far have been focusing on verifying existing human systems using these ISAs, we can use this same machinery to go beyond human limits: if we have both a model of a piece of software and its binary implementation encoded in Lean, we can use agents to super-optimise: LLMs can rewrite, distort and pervert the implementation freely to beat any benchmark, ensuring correctness by requiring that every optimisation is proven to preserve the semantics of the program.
For our LLM-written hyper-optimised FizzBuzz (née buzzsaw), we can instantiate this methodology as follows:
For any input n representing the number to count up to, our FizzBuzz
model describes the FizzBuzz sequence up to that n, and the eldritch
horror that is the LLM hyper-optimised buzzsaw binary is proven, when
run under the semantics of the assembly instructions, to produce an
equivalent bytestream output.
A Formally Verified, Super-Optimised FizzBuzz
Using LLM-powered super-optimisation, the final verified FizzBuzz was FAST. The buzzsaw binary measures around 336 GB/s of pure unadulterated FizzBuzz. It pumps out data at unimaginable rates, enough to fill a 2 TB drive in about six seconds, or, over a week, about 200 petabytes of FizzBuzz, roughly what the entire internet carries in 20 minutes. For reference, the previous best recorded human rate ran at a meagre 224 GB/s.
All of these numbers are written in the context of measuring FizzBuzz
piped into another program. In particular, the original 2020 Code
Golf Stack Exchange competition grading scheme is implemented as
./fizzbuzz | pv > /dev/null, where the pv tool records the
number of bytes as produced from its input pipe. Going fast means
getting bytes into that pipe as quickly as possible.
So how did the LLM-written FizzBuzz get so much faster than the
existing FizzBuzz implementations? The core of its speed and
efficiency comes down to some rather intricate details of how bytes are
output to the consuming program, all revolving around the syscall
vmsplice, and how threads output information.
In a normal program that you or I might write, we typically output
data using the write syscall – when this is called the kernel then
copies the supplied bytes out into the piped file
descriptor. Unfortunately, this means that normal programs usually incur
two rounds of copying – first by the kernel, copying the written
bytes into the pipe, and then second by the reader, copying them out
again.
The vmsplice syscall proposes a tantalising alternative methodology
– vmsplice instead hands the pipe a reference to the pages of the host
program's memory, eliding the first copy. The reader then reads the
bytes straight out of those pages. The devil is, as always, sadly in the
details, and the catch in using this syscall is that the producing
program must not touch the sent page of memory until the reader has
finished consuming it. vmsplice is the fastest way we know of to get
bytes into a pipe, and the fastest FizzBuzz programs all make use of
this syscall to achieve their numbers: the key determining factor then
in the final output speed boils down to efficiently coordinating
management of memory to satisfy this intricate choreography.
The three programs, Alex's original winning submission, David's
improvement, and the superhuman LLM buzzsaw, at their core are
different answers to "who generates bytes, who calls vmsplice, and
when":
Alex's original implementation opts for a highly optimised single-threaded FizzBuzz interpreter, which uses AVX2 instructions to compute chunks of FizzBuzz at once. Once a batch of memory is produced, the thread then calls vmsplice to publish the results and saunters on with the next batch.
To increase performance further, David introduces concurrency, splitting the construction of the FizzBuzz sequences into batches. David's code exploits a clever observation that if a batch's size happens to be divisible by 5, then "Buzz" will land in the same place in every batch, so the only task of the implementation will be to compute where to insert "Fizz", and update the leading digits. Each batch is then further split into chunks to compute in parallel. His implementation adopts a split-combiner (Hendler et al. 2010) style decentralised fork-join parallelism, where all the threads work on chunks of the current batch, and then the slowest thread is responsible for calling vmsplice. Once vmsplice is completed, then the next batch begins.
Buzzsaw builds on this batching observation, but takes the concurrency and parallelism to the next level, and implements a highly-parallel super-optimised pipelined process. In the buzzsaw algorithm, the available threads are split into several worker threads and one dedicated publisher thread. The worker threads non-stop tirelessly produce batches of FizzBuzz, using a custom CPU-tailored lockless algorithm to coordinate with the publisher thread which then calls vmsplice as soon as a run of slots is complete, with the sequences of ranges in memory that have been completed.
If Alex's algorithm was efficient, David's is a cut above. Buzzsaw is leagues above.
The algorithm
The core of the buzzsaw algorithm is an efficient ring buffer. The
program keeps a ring of R slots in memory, slot[R], and the threads
coordinate their writes to these slots through two pieces of shared
state: an array done[R], recording the last batch finished in each
slot, and a counter released, tracking how many batches have made
it all the way out of the pipe.
The batches are numbered 0, 1, 2, …, and batch j is always written into slot j mod R. Workers are preassigned batches of FizzBuzz, and with them the slots to compute them in, and the worker and publisher threads coordinate to efficiently publish results as soon as they are computed.
const R -- slots in the ring
const C -- bytes the pipe holds
const K -- worker threads
shared slot[R] -- buffers
shared done[R] := none -- last batch done
shared released := 0
worker (i): -- i = 0 … K−1
for m := 0, 1, 2, …:
j := i + m · K
s := j mod R
wait until released > j − R
write batch j into slot[s]
done[s] := j
publisher:
for j := 0, 1, 2, …:
s := j mod R
wait until done[s] = j
vmsplice(stdout, slot[s])
released := batches with ≥ C
bytes in the pipe after them
The publisher thread implements a simple algorithm where it walks
through the batches from 0 upwards. For each one, it waits until the
worker writing it has reported in done that the slot is filled, hands
the slot to the pipe with vmsplice, and then updates the variable
released to track which slots are free. A slot is free once the
reader has finished with the batch in it. The publisher cannot ask the
reader directly, but the pipe holds at most C bytes, so once C more
bytes have gone into the pipe after a batch, that batch must have been
read out; released counts the batches that have passed this point.
Each worker, meanwhile, works through its own batches. At each step, it
waits (in a spin loop) until released frees its slot for writing,
performs the writes, and once complete records the batch in done.
The key enabling mechanism for buzzsaw's efficiency here is that this
entire synchronisation uses no locks and no system calls: it relies
only on x86's memory model, which guarantees that a core's
stores become visible in the order they were made. So if the publisher
sees the write to done[s], then all of the worker's preceding writes
into slot[s] have also landed in memory.
The Formal Model
At 336 GB/s, the buzzsaw algorithm is clearly fast. But it is also subtle and complex. Especially given this eldritch machination was conjured up by an LLM, you may be sceptical that this efficiency might be through some cheating, or some bug, or implementing concurrency incorrectly. Is this really safe? And therein lies the rub! The beauty of buzzsaw is that, unlike all the human predecessors it stands before, it is also fully formally verified in Lean. There is no doubt about its correctness, but what exactly does this mean?
The buzzsaw algorithm relies on some subtle low-level details of the hardware and kernel, such as a CPU's memory model, page references and various syscalls. To ensure that these were used correctly, the LLMs verified it with respect to a formal model of the machine.
To build this model, the agents started from Kraken, which gives the
semantics of individual x86-64 instructions: what each one does to a
core's registers and memory. Kraken describes one core running on its
own, but buzzsaw runs on many cores at once, so the agents ported
x86-TSO on top of it. x86-TSO is the standard model of how x86
multiprocessors behave, due to Sewell, Owens and colleagues: each core
has a store buffer, a small queue where its writes wait before the CPU
moves them out to shared memory, oldest first. Finally, the agents
modelled the parts of Linux buzzsaw uses (the pipe, vmsplice, clone
and mmap) and the reader on the other end of the pipe, and added the
two instructions buzzsaw needs that Kraken lacked: 64-bit division
(div) and the spin-loop hint pause.
Put together, the model is one large state transition system. A state records all of these components at once, and each transition is one event that could happen during execution: a core runs an instruction, a store buffer drains, Linux handles a system call, or the reader reads.
To see how buzzsaw runs on this model, let's follow one batch through
the system. We start when a thread emits an instruction to write bytes
into memory (1). On x86, these bytes don't land in memory immediately,
instead they first sit in the core's store buffer, and the CPU drains
them into memory when convenient, in FIFO order (2). This ordering
guarantee is crucial to why the done marker can be used for
coordination: the worker writes done as the last store after it is
finished, so if the publisher can see a write to done, the batch is guaranteed to
have landed in memory (3). Finally, the publisher calls vmsplice, and
the pipe gets a reference to the slot's pages. The reader copies the
bytes out whenever it gets round to reading them (4), which is why
slots must not be touched until they have left the pipe.
With the model in place, the agents then proved two key properties about buzzsaw to ensure its correctness:
- First, safety, says that whatever the reader has seen so far is always a prefix of FizzBuzz, however the threads' steps interleave and whenever the store buffers drain.
- Second, completion, says that if the scheduling of threads is fair, i.e. every thread is scheduled infinitely often, the process will terminate having printed exactly the first n lines of FizzBuzz.
Alongside the system model, the proofs make two additional assumptions
about the external world: first that the reader copies the bytes out
of the pipe, as pv does, rather than splicing the pages onward, and
second that nothing else resizes the pipe while buzzsaw runs. Both of
these assumptions are implicitly also required by the two preceding
best human implementations.
Performance
Beware of bugs in the above code; I have only proved it correct, not tried it.
— Donald Knuth
Proofs only get us so far. Let's move onto the real deal. That's right. Running this bad boy on bare metal.
We ran our experiments on two machines: a Ryzen 9 9950X (Zen 5, Linux
7.0, mitigations off), and a Ryzen 9 5950X, the CPU the original
competition was judged on. Every program was pinned to its cores with
taskset. Each point is the mean of 10 runs (5 for the pv sweeps).
How fast a FizzBuzz program goes also depends on what is reading from
the pipe. The original competition's grader was using the command
./fizzbuzz | pv > /dev/null, and we do include plots for those however
it's possible to obtain higher throughputs with different
readers. David's Code Golf Stack Exchange post mentions that his optimal
scores use pv -B 2M so we also compared against that. We also measured
with a minimal reader that uses splice. The readers differ in what
they do with the pages. pv copies every byte out of the pipe into its
own buffer, while a splice reader just moves the page references on,
so it measures how fast the program can fill the pipe.
With the splice reader on the 9950X, buzzsaw peaks at 336 GB/s against 324 GB/s for David's program, and the plot below shows the throughput comparison. Buzzsaw consistently outperforms the human record, and buzzsaw's slowest run (333.9 GB/s) was faster than David's fastest (327.0 GB/s).
With David's own command, pv -B 2M, buzzsaw is still ahead, at 338
against 323 GB/s on the 9950X and 287 against 241 GB/s on the original
competition's 5950X.
Under the competition's original rule, plain pv, the reader becomes
the bottleneck, and both programs peak at about the same rate (194
against 192 GB/s on the 9950X). From 9 cores up, though, buzzsaw holds
around 160–180 GB/s while David's program drops to about 90, and the
5950X shows the same pattern.
For 1–3 cores, there are too few cores for a dedicated publisher, so buzzsaw's numbers there come from a variant in which the workers take turns publishing.
Conclusion
In this blog post, we usher in the end of an era. In 2020, the race began when a user on Code Golf Stack Exchange asked how to write the fastest FizzBuzz. This spurred a burst of human innovation, from Alex's hand-written assembly, and later David's concurrent C++, valiant efforts which pushed the fastest human score on the board to an insane 224 GB/s. Those answers were a demonstration of an art, of a craft, of an expert systems programmer and what they can do when pushed to optimise the simplest program there is.
That era is over. In a couple of weeks, LLM agents with Lean wrote a FizzBuzz faster than the human record at every core count from 1 to 15, and proved it correct down to the bytes of the binary.
This blog post is NOT about FizzBuzz.
The era of systems engineers is over. Humans need not apply. The fastest FizzBuzz is machine.