1260 points · by luu · 5y ago · 255 comments
These properties however don't diminish the achievement of leveraging AVX-2 (or any vectorization) for a problem that doesn't immediately jump out as SIMD.
The problem description is writing out bytes which is probably some of the more expensive part of this. In fact, if you read the winning solution description, IO is the primary problem here.
> doesn't immediately jump out as SIMD.
IDK that I agree with this assessment. Very naively, I see no reason you'd not take the 512 SIMD registers and split them into 16 32 bit lanes. From there, it's a relatively simple matter of using 2 registers for the divisors, pulling out the results, and transforming them into the text to print. In other words, you be chunking this up into 16 iterations per loop. (vs 1 with the naive assembly).
This is the sort of thing that jumps out as easily vectorizable.
Now, the fastest answer very obviously does not take this approach because I'm certain they realized the same thing, that the difficult part here isn't the actual division, but instead pumping out the correct text at the highest speed possible. If you read through it, most of the code is dedicated to converting binary numbers into ascii :D
As for the second point, you might have a different definition of "naive" and "relatively simple" as my brain has rotted too much from only thinking about SIMD for numerical computation. While determining divisibility be relatively clear, it wasn't clear how the printing would be easily vectorizable as the output-per-number is variable in length.
I think this nails it. Vectorizing the math problem is "easy" (send batches of numbers to cores, do the division) but then you have to re-order it for printing (not to mention actually print it), so paradoxically, it probably makes more sense for the program to be single-threaded.
As OP stated, the limiting factor is on the memory access. That's why he kept saying 64B every four cycles.
But OP likely didn't use because most CPU lacks support for AVX512.
The new Intel CPU introduced many changes for the frontend. This will likely improve the speed.
There might also be possible to try make the CPU operate at higher clockspeed.
Code looks a bit long. Not sure if the unrolling actually helps.
EDIT: Just look at the agner microarchitecture doc. Ice Lake and Tiger Lake can do 64 bytes/cycle.
In theory, it can run 4x faster (on bare metal, maybe).
I'll argue that, as a percent, the number of people who can write proper multi-threaded code has only diminished over the years.
And we see the result, despite the massive increase in computing power, software in general has become slower and bloated.
If you have "months to write fizzbuzz" levels of resources available, sure, you can microoptimize everything. Except in practice you can't, because the amount of effort needed for this kind of microoptimization is quadratic or worse in the complexity of the problem you're actually solving.
For a realistic-sized problem, if you write solutions in C and Python with the same amount of effort from equally skilled programmers, the Python version will almost certainly be faster, because they'll have had a lot more time available to spend prototyping and picking good algorithms rather than debugging undefined behaviour because they used the wrong combination of integer bit lengths.
The problem with modern software is that vendors encourage new developers to learn using heavyweight toolkits because lock-in is profitable in the long run. One day Electron will work with Go, but it will still be a plague.
The working set depends on how you organize the data. I/o can be made in larger chunks most of the times. You have to consider about the data you need and when you need it.
As for branching, that most of the time depends on programmer rather than on the problem being solved. The situation where you need very complicate branching to solve a problem are rare. And I've seen O(n log n) algorithms beating clever O(n) algorithms because they could be better optimized for the CPU.
It's a single transformation applied to elements of a large array. Parallelization is obvious, and maybe the exact SIMDization is not obvious, one is certainly motivated to formulate it. And a scatter-like approach does spring to mind right away, I believe.
It should never branch.
Once upon a time most software was highly optimized with hot code paths written in assembly. If you look at DOS source code, DOOM source code you will see lots of optimization.
When CPUs got more powerful, people got lazy and they thought they can spend the improvements on conveniences.
Now we are at the point that we run "desktop" apps written in Javascript on top of embedded browsers.
If you look at VSCode code, you’ll see even more of these. What really changed was more people wanted to hack things and write non-PhD code, and the web tech was (sadly) popular enough to take this role. It’s not programmers who are lazy, it was that desktop frameworks utterly failed in their non-competive niches. MSVC libraries replaced each other almost faster than github’s new web frameworks, to the point that barely anyone can remember their chronology. Gtk+ got stuck for years dealing with C legacy, added non-C styling engines too late, and then got “owned” by a particularly deteriorating DE. Qt always had a not-so-clear position on community-licensed versions, and C++ impedance mismatch didn’t help that either. UI/AppKits got pretty useful and advanced in recent ~ten years, but were ios/osx only. Minor frameworks like fox, wx, fltk, etc never got enough traction or new ideas and were just shadows of their bigger brothers. Meanwhile, with electron, bootstrap and little js one can make a page in few minutes, which could take few hours on conventional desktop.
I mean, you are correct that programming went from hardcore to relaxed mode, but there is more history to it in ui sense.
Because it will live for many years. It will have to survive in the hands of multiple caretakers. It will have to evolve to work with the underlying foundations changing (operating system, compiler/runtime, desktop -> web -> mobile).
That's different from most video games (one single release, then little patches) and from advent calendar code.
I mean I could probably hyperfocus on storing my application state in a file on disk, but why should I bother when there's off the shelf SQL databases right there? Which have been optimized endlessly, I might add. I don't get paid to write low level ASM, I get paid to build applications.
Edit: And to add, my current thing I get paid for is several orders of magnitude faster than the one it replaces. Not because I spend more time optimizing, but because I write it in sensible Go instead of 10K LOC PHP files that concatenate XML strings that get converted to JSON to be rendered in Dojo-flavored HTML concatenated together in JS because of reasons.
The market demand seems more like:
Jack: "Our bellowed CEO wants us to deliver our wonderful app to unwashed masses still using a desktop. Our enlighted marketing team made a study which realized that for whatever weird reason, corporations and businesses still make heavy use of those boxes which come with a mouse and keyboard attached."
Joe: "Sure thing boss, we will have to hire some programmers and testers and will take about a year or so."
Jack: "I forgot to tell you that the marketing study already took a year and a very large budget because we hired the best of the best to do it. One year we don't have, money we don't have. But what about those people who wrote our web app? We still pay them. Can't they deliver?"
Joe: "We will have our glorious desktop app in two weeks, boss, I just had an idea."
Jack: "Do that and I will personally remind about you to our bellowed CEO when he will want to do some promotions."
The power dynamics of companies/customers are often not as dynamic as all that.
If slack is electron and I work at a company that uses slack: I must use it.
The competition in that space is all electron, you can’t choose.
It’s like saying that “the market chose non-ECC ram”. No, Intel chose for you and you don’t get much choice except to suck it up (or pay well above the odds.)
It takes a lot to avoid using a product. I mean people still use Oracle products!
The market surely pushes against the bloated electron apps, yet the convenience of having the same app on web as well as "native" and the amount of man years which went to make HTML+JS the richest multi-platform UI framework on the market is more important.
It's not really a good argument is it?
A few years ago, I was doing Project Euler problems, and one of them had a solution that took about 45 minutes for my C program to solve. I decided that it was an incredibly simple problem, so rewrote it in Assembly.
My assembly solution took an hour to run.
I disassembled my C solution, and couldn't figure out what it was actually doing, though my assembly knowledge is pretty weak.
I see many people having trouble to understand the difference between value and reference, what pointers are, why it's better for structures to contain variables of the same type and have a certain size, why is better to call a function once for a large chunk of data instead of calling it many times for small chunks of data, why iterative or tail call recursivity are to be preffered over simple recursive functions.
The view is most LOB apps won't care about performance because they are waiting for i/o so we should not care about performance but coding speed, OOP, Uncle Bob's principles, GoF patterns, Restful and trendy architecture of the day. While I sure that coding speed matters, a sound architecture matters, I also think that throughput matters, that minimizing delays matters and that some problems are better dealed with by thinking of the data and how the CPUs likes to access data and work with it instead of just firing up more Kubernetes pods hoping that scaling will get rid of performance issues. By not thinking about the data and the CPU we didn't get rid of the complexity we just moved it to the infrastructure and in code having to deal with a more complex infrastructure.
I've always been curious about how far we could really push modern computers if somebody wanted to spend the time going to the lengths in the original post when creating practical software. Of course it's usually not worth the tradeoff, but it's interesting to think about.
while you made a great comment, ND people like me, and even most NT people have diffivulty ingesting walls of text like what you just wrote.
Please, therefore, breakup your text into paragraphs every 3 sentences. It does wonders for readability for just about everyone. :)
The benchmark was about getting the output to a pipe as fast as possible, and there's this great pipe speed hack:
// To produce output without losing speed, the program therefore needs
// to avoid copies, or at least do them in parallel with calculating
// the next block of output. This can be accomplished with the
// `vmsplice` system call, which tells the kernel to place a reference
// to a buffer into a pipe (as opposed to copying the data into the
// pipe); the program at the other end of this pipe will then be able
// to read the output directly out of this program's memory, with no
// need to copy the data into kernelspace and then back into
// userspace.Obviously finding talented staff is very hard, but once you have your tribe you can go a very long way i.e. I look at apps made by some people I work with (fast, lightweight etc.) then compare with crap pumped out by startups with literal billions in capital. I think it's a question of confidence more than competence.
Leaky abstractions are a different problem altogether.
Death by thousand cuts
Sure your Python/JavaScript/Haskell/Rust version builds on a bunch of abstractions, but it’ll run on just about anything, and …
“I've spent months working on this program”
That’s not what your boss wants to hear.
Unless your talking about micro controller programing Ram is basically free.
A larger amount of RAM might still be cheap to install in the first place, but that choice is not always directly up to the consumer.
End users are used to tolerating a basic chat application eating an indefinite amount of ram.
From a business pov it doesn't make sense to spend time optimizing since most users don't seem to mind.
Edit: don’t get me wrong! I admire the talent that goes into this and similar efforts, and find performance-chasing particularly inspiring in any context. This is just an area of that which I don’t anticipate ever wanting to tread myself.
> I've spent months working on this program
> I already have a master's thesis. This was harder.
Person who wrote this probably won't know much about, say, compatibilities of latest version of WebPack and VueX; or about cryptographic protocols.
You cannot know everything.
The last time I have seen this low level of code was in a college level course about assembly language.
Being able to write a function limited mostly by the l2 cache size and able to realize that is rad
And btw this is an interesting example of how hand optimized assembly can be much much faster than any other solution. Can you get as fast as this solution with mostly C/C++? It uses interesting tricks to avoid memcopy (calling it slow rofl)
And you probably can’t fine tune your C/C++ to get this performance without knowing exactly what processor instructions you are trying to trick the compiler into generating anyway.
In fact, in this case you know exactly what processor instructions the compiler is going to generate. You are using AVX intrinsics after all.
And no, compiler optimizations work well with these intrinsics.
Of course all the AVX and cache optimizations are also exceedingly clever.
///// Third phase of output
//
// This is the heart of this program. It aims to be able to produce a
// sustained output rate of 64 bytes of FizzBuzz per four clock cycles
// in its main loop (with frequent breaks to do I/O, and rare breaks
// to do more expensive calculations).
//
// The third phase operates primarily using a bytecode interpreter; it
// generates a program in "FizzBuzz bytecode", for which each byte of
// bytecode generates one byte of output. The bytecode language is
// designed so that it can be interpreted using SIMD instructions; 32
// bytes of bytecode can be loaded from memory, interpreted, and have
// its output stored back into memory using just four machine
// instructions. // [The eighth byte of LINENO_MID] changes in meaning over the course of
// the program. It does indeed represent the billions digit most of
// the time; but when the line number is getting close to a multiple
// of 10 billion, the billions and hundred-millions digits will always
// be the same as each other (either both 9s or both 0s). When this
// happens, the format changes: the hundred-millions digit of
// LINENO_MID represents *both* the hundred-millions and billions
// digits of the line number, and the top byte then represents the
// ten-billions digit. Because incrementing a number causes a row of
// consecutive 9s to either stay untouched, or all roll over to 0s at
// once, this effectively lets us do maths on more than 8 digits,
// meaning that the normal arithmetic code within the main loop can
// handle the ten-billions digit in addition to the digits below.https://www.righto.com/2018/04/fizzbuzz-hard-way-generating-...
I thought the exact same question, but wondered if FPGA's gate connections are too distant for FizzBuzz to beat 55 GiB/s.
If you require it to come out of IO pins, then the limit will be the total output bandwidth of all the serdes units on the IO pins. Typically that's much more than 55GiB/s.
But this task could be scaled up with parallel FPGA boards in sync
Regardless, I very much enjoyed your DVD screensaver-esque output.
And am I doing the math right that a quintillion fizzbuzz will take about 7 months?
It's so impressive and hilarious to me that he actually spent months on this. Well done!!
I've done stuff like this before, and I imagine the satisfaction of completing it! A tip of my hat to you, sir!
That's borderline incredulous, given a single AVX2 instruction can last multiple clock-cycles. The reciprocal throughput also doesn't go below ~0.3 to my, admittedly shallow, knowledge. A remarkable piece of engineering!
Note that the instruction latency is not important as long as you can pipeline the computation fully (which appear to be the case here!).
Edit: to go faster you would need to be able to use the bandwidth of more than one cpu. I wonder if you could precompute were the output will cross a page to be able to have distinct cores work on distinct pages... Hum I need a notepad.
Edit2: it is much simpler than that, you do not need to fill a page to vmsplice it. So in principle the code should parallelize quite trivially. Have each tread grab, say 1M numbers at a time, for example by atomically incrementing counter, serialize them to a bunch of pages, then grab the next batch. A simple queue will hold the ready batches that can be spliced as needed either by a service thread or opportunistically by the thread that has just finished the batch next in sequence.
FYI "incredible" might be a better word here. "Incredulous" would mean that it finds something incredible.
It worked well for the course and the results were very consistent between runs, but that kind of setup doesn't scale well.
There may be a (slow) option though, and that would be benchmarking the code using an simulated processor. The runtime would be measured relative to the simulated processor as opposed to the computer hosting the simulator.
EDIT: And a fizzbuzz co-processor, obviously.
One of the functional modules on the M1 Pro Max chip, but only the Max one, unfortunately.
Take that, Intel!
Also, even with a very slow CPU you'd already run faster than can be perceived on a digital clock
Ed: no, but does pretty well:
> The program outputs a quintillion lines of FizzBuzz and then exits (going further runs into problems related to the sizes of registers). This would take tens of years to accomplish, so hopefully counts as "a very high astronomical number" (although it astonishes me that it's a small enough timespan that it might be theoretically possible to reach a number as large as a quintillion without the computer breaking).
Splice is linux specific though, so you would need to run it on M1.
I find this programming it very beautiful and rewarding in that you really know that you are programming the hardware. Unfortunately it's not an easy path to get a good paying job (unless you are exceptional like the gentleman). So I ended up building fintech web apps.
Edit: yes it has a --no-splice parameter.
It turns out The Grid is just a guy sitting in a chair, shouting about "Fizz!" and "Buzz!" as fast as he can.
It wasn't really what I had in mind.
(The image of this poor program, stuck shouting "fizz!" and "buzz!" for subjectively centuries at a time struck me...)
> // Most FizzBuzz routines produce output with `write` or a similar
> // system call, but these have the disadvantage that they need to copy
> // the data being output from userspace into kernelspace. It turns out
> // that when running full speed (as seen in the third phase), FizzBuzz
> // actually runs faster than `memcpy` does, so `write` and friends are
> // unusable when aiming for performance - this program runs five times
> // faster than an equivalent that uses `write`-like system calls.
Why can't `write` use a reference like vmsplice?The issue is that the caller to write is allowed to do anything it wants with the buffer after write returns, so the write implementation need to unmap the stolen pages and perform copy on write if the caller ever touches them again, so in practice the optimization is very fragile. For this reason Linus as always refused to implement this optimization.
Splicevm gets away with it because it is part of the caller contract that it can't ever touch the pages until the kernel is done with them. Unfortunately there is no general way to know when it is safe to reuse them and it is very application specific (for example there might be an explicit ack from the consumer that it has received the data)
But yeah, frequency illusion.
Wow.
From the opening question on that page "A naive implementation written in C gets you about 170MiB/s on an average machine" and that C code is typical, there's nothing drastically bad about it. C already has a reputation as a fast, low level language. This answer is running over 320x faster than the straightforward C answer on the same hardware. If you asked people "how much faster can it possibly get without moving to specialist hardware", I doubt they'd guess that high.
It's difficult to get higher speed by using more CPU cores because calculating FizzBuzz is much faster than printing it so they'd just fill up a queue and then stall waiting. To get faster, people are leaning on what exactly is happening internally, adjusting buffer sizes and how to generate the text "FizzBuzz" and get it into the right place to be printed at the right time, and which system calls can be done with less overhead, and lining up more work which can happen during the pauses, and unrolling loops to give the CPU a pattern of instructions it can execute quicker, this is getting answers into the GB/sec ranges.
This answer is like the Bugatti Veyron of answers; so finely tuned it's surely getting close to the limits of what the hardware can do. Making use of AVX2 registers which can hold 32 bytes instead of 8, and can be vectorised so one instruction processes many pieces of data, which means less overhead of instructions for the CPU to decode and process per piece of data, and deeper magic, a lot of skill and knowledge required to put all of it together.
And of course, someone spending months trying to send "Fizz" and "Buzz" into a counter at tens of billions of bytes per second for no good reason, is amazing in a different way.
[1] A nonsense back of an envelope estimate, but good enough for context.
[1] https://aphyr.com/posts/340-reversing-the-technical-intervie...
// The third phase operates primarily using a bytecode interpreter; it
// generates a program in "FizzBuzz bytecode", for which each byte of
// bytecode generates one byte of output. The bytecode language is
// designed so that it can be interpreted using SIMD instructions; 32
// bytes of bytecode can be loaded from memory, interpreted, and have
// its output stored back into memory using just four machine
// instructions.
// The bytecode format is very simple (in order to allow it to be
// interpreted in just a couple of machine instructions):
// - A negative byte represents a literal character (e.g. to produce
// a literal 'F', you use the bytecode -'F', i.e. -70 = 0xba)
// - A byte 0..7 represents the hundreds..billions digit of the line
// number respectively, and asserts that the hundreds digit of the
// line number is even
// - A byte 8..15 represents the hundreds..billions digit of the line
// number respectively, and asserts that the hundreds digit of the
// line number is odd
// %ymm2 holds the bytecode for outputting the hundreds and more
// significant digits of a line number. The most significant digits of
// this can be obtained by converting LINENO_TOP from high-decimal to
// the corresponding bytecode, which is accomplished by subtracting
// from 198 (i.e. 256 - 10 - '0'). The constant parts of LINENO_TOP
// are 198 minus the bytecode for outputting the hundreds to billions
// digit of a number; this makes it possible for a single endian
// shuffle to deal with all 16 of the mid and high digits at once.I'll watch it later.
Speaking for myself: between caring for a puppy, cognitive impairments from ADHD, sustained impact from burnout, and financial responsibilities for family… my ability to carve out free time for a very long list of things I’d like to do extracurricularly is limited to a few hours a week at most. Achieving a “months of work” project in my areas of interest and applicable talents is easily going to take 10x as long. And that also means being much more circumspect about where I choose to focus those interests.
But I mean, obviously, yes. Different people can do different things for a zillion different reason. I'm reacting negatively because it sounds like a criticism against the author just for spending a lot of time working on a hobby project just for the sake of it.
See also: "why are you having fun when cancer still isn't cured yet?"
Here! You forgot the sarcasm mark :)
This is mind blowing to say the least!
It's actually a fairly common pattern, both ffmpeg and the Linux kernel do this for example.
#include <sys/syscall.h>
is generally the easiest way to make a syscall without hardcoding numbers into your assembly program.At that point my coffee time ran out. I wish I had more time to figure out why. :-(
Edit: actually it sounds like it’s more cache efficient because it can always use the same block of cache memory?
This is the heart of this program. It aims to be able to produce a
sustained output rate of 64 bytes of FizzBuzz per four clock cycles
in its main loop (with frequent breaks to do I/O, and rare breaks
to do more expensive calculations).
The third phase operates primarily using a bytecode interpreter; it
generates a program in "FizzBuzz bytecode", for which each byte of
bytecode generates one byte of output. The bytecode language is
designed so that it can be interpreted using SIMD instructions; 32
bytes of bytecode can be loaded from memory, interpreted, and have
its output stored back into memory using just four machine
instructions. This makes it possible to speed up the FizzBuzz
calculations by hardcoding some of the calculations into the
bytecode (this is similar to how JIT compilers can create a version
of the program with some variables hardcoded, and throw it away on
the rare occasions that those variables' values change).
The bytecode format is very simple (in order to allow it to be
interpreted in just a couple of machine instructions):
- A negative byte represents a literal character (e.g. to produce
a literal 'F', you use the bytecode -'F', i.e. -70 = 0xba)
- A byte 0..7 represents the hundreds..billions digit of the line
number respectively, and asserts that the hundreds digit of the
line number is even
- A byte 8..15 represents the hundreds..billions digit of the line
number respectively, and asserts that the hundreds digit of the
line number is odd
In other words, the bytecode program only ever needs to read from
LINENO_MID; the information stored in LINENO_LOW and LINENO_TOP
therefore has to be hardcoded into it. The program therefore needs
to be able to generate 600 lines of output (as the smallest number
that's divisible by 100 to be able to hardcode the two low digits,
200 to be able to get the assertions about the hundreds digits
correct, and 3 and 5 to get the Fizzes and Buzzes in the right
place).
The bytecode interpreter consists of four instructions:
1. Load the bytecode from memory into %ymm2;
2. Use it as a shuffle mask to shuffle LINENO_MID_TEMP;
3. Subtract the bytecode from the shuffle result;
4. Output the result of the subtraction.
#define INTERPRET_BYTECODE(bc_offset, buf_offset) \
vmovdqu %ymm2, [%rdx + bc_offset]; \
vpshufb %ymm0, LINENO_MID_TEMP, %ymm2; \
vpsubb %ymm0, %ymm0, %ymm2; \
vmovdqa [OUTPUT_PTR + buf_offset], %ymm0A ticket for this work has been made at here: https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpris...
I'm going to have to ask that the contributors attend the grooming sessions and talk about the business value of this performance enhancement.
FizzBuzzOutputGenerationContextVisitorFactory.java
file.