389 points · by orlp · 3y ago · 70 comments
I will be giving a talk on glidesort tomorrow at FOSDEM 2023 in the Rust Devroom at 16:10, you can seek me out there as well. In other news, I am leaving academia soon, so if you have interesting (Rust) jobs the coming months feel free to approach me.
Commands to run to replicate my results are below. Clone rhsort and run them in that directory. The res/*.txt results are human-readable but you have to install my programming language[2] to generate the plot. Hey, you made me program in Rust.
[0] https://gist.github.com/mlochbaum/7664a046d294dcce2f6cdb1db6...
[1] https://github.com/mlochbaum/rhsort
[2] https://github.com/mlochbaum/BQN
./wolfbench.sh
mkdir res
gcc -O3 -D NOTEST bench.c && ./a.out l > res/r_rh.txt
gcc -O3 -D FLUXSORT -D NOTEST bench.c && ./a.out l > res/r_flux.txt
gcc -O3 -D WOLFSORT -D NOTEST bench.c && ./a.out l > res/r_wolf.txt
g++ -w -fpermissive -O3 -D SKACOPY -D NOTEST bench.c && ./a.out l > res/r_ska_.txt
cd glide && cargo build --release && cd ..
gcc -O3 -D GLIDESORT -D NOTEST bench.c -Lglide/target/release -lglide
LD_LIBRARY_PATH=glide/target/release ./a.out l > res/r_glide.txt
images/line.bqn res/r_{flux,wolf,ska_,glide,rh}.txt > images/rand_glide.svg glidesort = { version = "0.1.1", features = ["unstable"] }
To get the best performance I use specialization for Copy types (such as integers) to compete with the assumptions that fluxsort and such can make, which is not available on stable Rust (unless glidesort were to be merged into the standard library). Without that I have to be more conservative with bounds checks. And even then there's a variety of places where I sacrifice performance compared to fluxsort and such in the name of safety, and the limitations that Rust gives me (in particular panic safety has cost me 10-15% performance).Also when you say x86, I assume you mean x86-64? I have not tested raw x86. What is your actual processor?
EDIT 2: I believe this should also go in the Cargo.toml of glide in your repository, not in a .cargo/config
[profile.release]
lto = "thin"Does panic safety really cost 10-15% when sorting integers according to default comparison?
Either way, I am not surprised that glidesort is a bit slower than fluxsort on older machines. They're less likely to take advantage of the interleaving techniques I use.
> Does panic safety really cost 10-15% when sorting integers according to default comparison?
Yes :(
At least yes, if you don't want to duplicate your entire codebase. Look into the code of glidesort if you want to, all algorithm state has to be encoded inside structs at all times, to allow for recovery in case a comparator panics using the destructor.
This negatively affects the optimizer for reasons I can't fully explain compared to having the state be in simple local variables.
I'm not surprised fluxsort is slightly faster, it's heavily optimized for gcc -O3.
Since the primary techniques that give glidesort it's speed were copied from fluxsort and quadsort I'm expecting very similar performance, and possibly significantly worse performance on strings due to accessing 4 memory regions.
Have you gotten it working with the wolfsort benchmark?
I was planning to update my repository to grab the appropriate files from the fluxsort repository but if you'd update the wolfsort repo I wouldn't have to. Although maybe I should switch over to cloning fluxsort instead.
The latest fluxsort is probably identical on random, the new analyzer might perform slightly better on modern hardware.
Probably safer to stick with wolfsort as I do tend to make sure that works with rhsort when I update.
I wonder how many times per day (or, indeed, per second) my computer does sorting of any kind. I just checked a largish codebase I'm working on, and about 0.12% SLOCs invoke the standard library's sort. But that's just a random codebase. What about the kernel, the browser, the VMs, the graphical subsystem of the OS? Could I capture all these sorts' inputs to generate My Real-Life Sorting Corpus of One Day's Worth of Data? And then compare the performance of different sorting algorithms on that corpus?
I'm pretty sure this kind of research has been done before. Can someone point me towards relevant literature?
You could wrap the lib containing the sort function and write the input to some file.
It is easy of it is C at least.
Instruction wise this is not true either. Sorting is a O(N log n) problem and log n is never going to be above 64. A cpu spending lots of time sorting implies that it is constantly throwing away the sorted results.
Keep in mind that glidesort is partly derived from fluxsort and many of its techniques were directly inspired by fluxsort/quadsort, while several others are implemented in a similar or near-identical manner. This is in my opinion not adequately explained in the presentation on youtube.
The main difference is that glidesort uses timsort's approach to adaptive sorting rather than quadsort's, though it uses quadsort's novel method for cost-effective branchless merging.
Glidesort tries to access 4 memory regions instead of 2, primarily with the bidirectional partition, an approach I implemented in 2021, but rejected because it was causing degraded performance for expensive comparisons. This does however result in a very different visualization which can give the impression it is unrelated. The general approach to stable partitioning is likely nearly identical to fluxsort.
As for why blitsort is fast, it's likely due to trinity rotations and monobound binary searches. Possibly also a more optimal overall partitioning strategy.
I haven't spend too much time on blitsort however, so there are likely further improvements to be made.
We've had an extensive email discussion on this, and I still have to publicly provide counterweight.
Yes, I did look at fluxsort/quadsort (mostly the README descriptions) while developing glidesort, I did get inspired by fluxsort's stable quicksort performance. And I did take quadsorts 'parity merge' idea for small sorts, as I described here 9 months ago: https://news.ycombinator.com/item?id=31101498. I'm open about this.
But you're not the first to do branchless merging, I was already aware of that in "Branch Mispredictions Don't Affect Mergesort". Ping-pong merges turns out were already described in "Patience is a Virtue: Revisiting Merge and Sort on Modern Processors".
The observation that the reason the 'parity merge' was so fast being instruction-level and memory-level parallelism is my own (you added this to the README after I publicly described this in the above linked comment). That we can then use it more generally as a bidirectional merge is my own. Using merge splitting and lazy merging to then apply this to more merges is my own. Interleaving multiple independent merge loops is my own. Extending the quicksort to then also use bidirectional partitioning is also my own idea (I don't have a crystal ball about you implementing and rejecting the idea in 2021). My pivot selection is my own. The whole extension of powersort to use lazy merging and more merge splitting for ping-pong merge opportunities is my own. The novel robustly adaptive combination of merge and quicksort is my own. I've spent months and months optimizing glidesort. Glidesort tackles problems fluxsort/quadsort don't even have to worry about in being unable to copy values, only move them, and dealing with panics from user-provided comparator functions, and comes out with minimal losses.
You do great work Igor, but I would appreciate it if you would stop try to claim mine as (mostly) yours.
"Since the parity merge can be unrolled it's very suitable for branchless optimizations to speed up the sorting of random data. Another advantage is that two separate memory regions can be accessed in the same loop with no additional overhead. This makes the routine up to 2.5 times faster on random data."
I described what made it fast and it was obvious there was general applicability. If I understanding your reasoning correctly, because you took inspiration from my more advanced unguarded two directional merge, you feel like a guarded two directional merge is some new novel discovery.
This is a very contentious line of reasoning.
Subsequently you then proceed to give me zero credit for branchless merging in your Youtube presentation, instead referencing a branchless merge that gave a 10-20% speed-up instead of quadsort's 150% speed-up. You also claimed in the presentation there were no bidirectional branchless algorithms written to date, this is simply not true.
This does upset me. It would be a simple matter, and the right thing, to point out that quadsort introduced bidirectional branchless merging.
As for your work to increase the memory regions from 2 to 4. This is easily conceived, but indeed quite challenging to actually implement.
The fact that glidesort can use small amounts of memory is honestly a happy coincidence of the merge-splitting technique I do that I only realized during development, and was not a primary goal.
The default allocation size is hard to describe in plain English, whereas the code is quite readable:
const FULL_ALLOC_MAX_BYTES: usize = 1024 * 1024;
const HALF_ALLOC_MAX_BYTES: usize = 1024 * 1024 * 1024;
fn glidesort_alloc_size<T>(n: usize) -> usize {
let tlen = core::mem::size_of::<T>();
let full_allowed = n.min(FULL_ALLOC_MAX_BYTES / tlen);
let half_allowed = (n / 2).min(HALF_ALLOC_MAX_BYTES / tlen);
let eighth_allowed = n / 8;
full_allowed.max(half_allowed).max(eighth_allowed)
}
Essentially the default allocation size is a linear graph M(n) = n until 1 MiB, where it will plateau until overtaken by M(n) = n / 2 until 1 GiB, where it will once again plateau until overtaken by M(n) = n / 8.Note that this is only the default, you can pass glidesort a buffer with a size/location of your choice and it will use that instead.
How does the algorithm stay bounded in memory usage? Is glidesort written in such a way to never use more memory than that? Is the some sort of back-pressure mechanism, when most of the allocated memory is in use, and another operation is ongoing? Basically: when sorting a 1 GiB array of data, how does the algorithm keep from using more than 128 MiB of additional memory? Nothing in the "Technique Overview" section mentions bounded memory use (under n bytes, at least).
It does not ever allocate more than what it allocated at the start.
> Is the some sort of back-pressure mechanism, when most of the allocated memory is in use, and another operation is ongoing?
Yes and no. I did write some code that will make glidesort back off and use less memory if the allocation request fails:
https://github.com/orlp/glidesort/blob/master/src/lib.rs#L20...
The sad part is that this will probably never work in reality due to overcommit.
> Basically: when sorting a 1 GiB array of data, how does the algorithm keep from using more than 128 MiB of additional memory?
By allocating 128 MiB at the start, and never allocating more than that.
Maybe what you really want to know is: how can it do merges in space (much) smaller than the input? The answer is by (recursively) splitting merges into two separate smaller merges using an in-place block swap. You can see this in action at the 10 to 12 second mark here: https://user-images.githubusercontent.com/202547/216675278-e...
Because I use block swaps and not rotations, this block swap can often be done implicitly (just not in the case of low-memory fallbacks) by re-assigning buffer names rather than physically moving elements.
Note that this all happens on a single thread, this is in addition to thread-level parallel sorting (which glidesort does not (yet) have).
Also note that this is different than SIMD, which processes more data in a single instruction. This can give you incredible speed-ups, but the code is very dependent on the data (e.g. code for sorting integers looks very different than sorting strings with SIMD). Glidesort is written using scalar code with fully generic comparison functions, no SIMD-specific speedups.
> In a traditional "merge" algorithm, the second comparison depends on the output of the first, so it can't be done at the same time. So it might make sense to merge "from the left" and merge "from the right" at the same time because those things can be done in parallel when both arrays have length > 1.
?
https://i.imgur.com/AUOJ1w0.png
https://i.imgur.com/AP6DnIS.png
Note that the four bottom sorts (RustSort, StdSort, Pdqsort, IPS4o) are not stable. GlidesortN is glidesort using n elements of memory, Glidesort is the default memory setting and Glidesort1024 uses a fixed 1024 element buffer.
Arm is a 2021 Apple M1, Amd is a 2018 Threadripper 2950x.
One thing glidesort appears to do extremely well is to branchless merge till the very end, this gets quite tricky when memory constrained. It does not seem worth it intuitively, but judging from the performance of rotate mergesort, it probably is.
And there was some prior discussion on HN here: https://news.ycombinator.com/item?id=33827843
Would love to try this out, though the source looks... difficult for me to do a naive port.
To compare across languages I simply implemented the exact same benchmark twice, once in Rust and once in C++.
I recognize that in practice vs in theory is often an issue and have had to deal with it myself in the past, but seriously sorting seems specifically awful to deal with.
What should be mentioned is that there's a variant (requiring memory XYZ) that is stable. It would be fair to call it a variant of the quicksort algorithm.