Lurker News
Hi all, I've talked about glidesort a few times on HN already, but it's finally ready for release. If you have any questions, feel free to ask. An academic paper on glidesort that goes into a lot more detail than the readme is upcoming, but is not ready yet.

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.

Comments (70) 12 threads

mlochbaum2 replies#
I was able to get glidesort running as part of the Robin Hood sort benchmark[1]. See [0]; it's a lot slower than fluxsort on random data. Wondering if I did something wrong. Is cargo build --release with rustc 1.64.0 enough? Tried lto = "thin" in .cargo/config as well, which is ever so slightly faster. Also tried passing in a buffer one, then two, times the input length which didn't change things. Was this tested on x86?

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
orlp1 reply#
Try running with the latest nightly Rust (`rustup update nightly`) and with `cargo +nightly build --release`. EDIT: I'm sorry, you need to specify this in your Cargo.toml, my earlier command was incorrect:

    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"
mlochbaum1 reply#
Updating my system, going to take a little while... Partner in crime dzaima has tested (nightly, unstable, lto) and found it is somewhat better. Eyeballing, still ~20% slower than fluxsort. We're on fairly old Intel x86-64 CPUs, i5-6200U for me and i3-4160 for him.

Does panic safety really cost 10-15% when sorting integers according to default comparison?

orlp11 replies#
I get these results for your benchmark on my machine: https://gist.github.com/orlp/d7123ede0143e15ab0f8a435b7dd10b...

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.

Continue this thread — 11 replies

scandum1 reply#
I recently upgraded fluxsort, you might want to give v1.1.5.4 a spin. I also updated the benchmark to use actual natural runs and be less favorable to rhsort, sorry. ;-)

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?

mlochbaum2 replies#
I did actually test out 1.1.5.4 in advance of this. I just used saved results instead of the new version for comparison because performance appears very similar on random inputs. I do see a lot of improvement in quadsort and most of the special-case benchmarks.

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.

scandum#
I'm planning to update wolfsort soon-ish. I did some work on a dropsort hybrid, like rhsort, though it's slower overall because I'm not quite brave enough to match the level of insanity (I mean this in a good way) that rhsort engages in.

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.

scandum6 replies#
I went ahead and updated bench.c for the wolfsort github.

Continue this thread — 6 replies

nathell3 replies#
This got me thinking about sorting.

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?

rightbyte1 reply#
> Could I capture all these sorts' inputs to generate My Real-Life Sorting Corpus of One Day's Worth of Data?

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.

nathell#
It is easy enough to wrap libc's qsort() with LD_PRELOAD, sure. The problem is heterogeneity: qsort() is by far not the only sort implementation the machine is running. Even identifying them all might be a daunting task, not to mention figuring out how to wrap them.
mtlmtlmtlmtl#
Sounds like the sort of thing dtrace or bpftrace might be able to do.
anacrolix3 replies#
sorting and searching are like 50% of what the CPU ever does. the benefits of ground breaking improvements there are huge. makes me think of proebsting's law, I don't know if this applies here.
CyberDildonics#
This is not true. Power and transistor wise most of what a CPU does isn't even about running instructions, it is instruction reordering, cache, speculation, prefetching, write queueing and other techniques to minimize the effects of memory latency.

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.

adgjlsfhk11 reply#
Pretty sure something like 80% of CPU time and power is spent pointer chasing in bad OO code.
andromeduck#
I'd imagine that or string ops.
saagarjha#
Not at all. Try running perf against your computer and you’ll see differently.
10000truths2 replies#
I'm interested in seeing a comparison with blitsort. Like glidesort, it's stable, adaptive, and can be configured to use constant auxiliary memory.
orlp#
I haven't done a comparison yet (because I haven't gotten to really benchmarking the low-memory performance), but I will include it in the paper.

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.

scandum1 reply#
If the last presentation's benchmark still goes, blitsort is significantly faster.

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.

orlp1 reply#
> 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.

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.

scandum2 replies#
This is what quadsort's README stated in early 2021:

"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.

Continue this thread — 2 replies

timerol1 reply#
The ability to work with different memory sizes is pretty intriguing. How does the algorithm decide where and when to allocate?
orlp1 reply#
The allocation always happens once, at the start of the algorithm.

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(n: usize) -> usize {
        let tlen = core::mem::size_of::();
        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.

timerol1 reply#
I used the word "allocate" imprecisely. (The plain English description in the README did a good job of explaining the up-front allocation needs.) What I meant to ask:

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).

orlp5 replies#
> How does the algorithm stay bounded in memory usage? Is glidesort written in such a way to never use more memory than that?

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.

Continue this thread — 5 replies

Load more comments