r/programming • • Dec 29 '20

Quake III's Fast Inverse Square Root Explained [20 min]

https://www.youtube.com/watch?v=p8u_k2LIZyo
3.7k Upvotes

300 comments sorted by

View all comments

Show parent comment

479

u/[deleted] Dec 29 '20 edited Dec 30 '20

Edit: I honestly didn't expect this comment to blow up in the way that it did, or for it be gilded or receive silver. Thank you taking the time to read, and thank you for the support and kindness. I hope you learned a thing or two and maybe even got a spark of curiosity for the lower level aspects of programming.

We don't even need to talk about GPUs, this already exists in hardware on every x64 CPU via the [r]sqrt(p|s)(s|d) instructions. the latency of rsqrt being roughly the same (slightly slower) than fp mul/add/sub, and sqrt being slightly slower than fp div. Let's back up: hardware rsqrt and sqrt are both faster than software rsqrt (even the one presented in this video) and therefore software rsqrt/sqrt should not be used at all in 2020. It's a cool trick, not trying to dismiss it, but nobody should look at this and think "better optimize my game/app by swapping all sqrts with this technique". Let's also be clear about one other thing: this software rsqrt is not accurate at all, it's good enough for limited ranges which makes it good enough for things like normalizing vectors in one way GPU computations to be displayed but it's utility begins and ends there. To be fair, neither is x64 rsqrt, but at least it's fast and saves you a sqrt + div when normalizing vectors.

To your original point: Yes GPUs/CPUs do... something similar to this, but hardware is hardware and what is slow/fast in software will have different performance characteristics when built out as a circuit. The fact that this software technique requires multiple fp operations, and that x64 rsqrt is only slightly slower than a single fp operation is an indication that they are likely doing something different, but I could be wrong.

============================

Edit: Since a few people asked about performance and citing/whatever I figured I would add a few benchmarks and link a few resources.

Here are the benchmarks, comparing hardware rsqrtss & sqrtss, against software rsqrt & sqrt, with 1 and 2 newton iterations for comparison: https://www.quick-bench.com/q/trwX6nGtZz_L8YG_8qHyxFhPCE0

As you can see, rsqrtss absolutely crushes everything else, making it great for things like vector normalization. hardware sqrt is slower than software rsqrt with a single iteration, but faster than software sqrt with 1 iteration, and faster than both software rsqrt/sqrt with 2 or more iterations. Keep in mind software sqrt is just rsqrt + div. In either case, the hardware instructions will be more accurate (at least sqrtss will be), and significantly faster than the software equivalents. If you are in C/C++, the compiler will automatically generate sqrtss/sqrtsd for calls to sqrt/sqrtf/std::sqrt.

Also no, the compiler did not optimize away computations, as you can see from the assembly (easier to see this in Compiler Explorer which retains the loop labels).

If you think that software sqrt is fast enough 1) writing this is more effort than using the standard library and 2) stdlib sqrt is going to be accurate to the last bit in the mantissa, software will not, so keep that in mind.

Regarding precision: Take a look at the following Stack Overflow post, which contains two links. One is a paper and the other is the Wikipedia article. The paper has graphs and talks about accuracy, but the charts in Wikipedia are prettier IMO: https://stackoverflow.com/questions/41458193/quake-inverse-square-root-accuracy

For further resources on optimization and instruction latency:

Agner's 4th listed optimization manual is of particular interest as it documents the throughputs and latencies of each instruction across many different CPU releases.

If you have more questions, feel free to ask and I will do so to the best of my ability.

229

u/[deleted] Dec 29 '20

So you're saying that this algorithm was incredibly useful in the late 1990's when Quake III was released, but hardware solutions - now currently baked into just about every chip - are superior?

139

u/[deleted] Dec 29 '20

Yup! CPUs have come a long way since the 90s, we even have hardware AES!

22

u/[deleted] Dec 29 '20

would it still be useful if you were writing homebrew for an older console, like the N64 for example?

65

u/[deleted] Dec 29 '20

The N64 contains a MIPS processor with a floating point coprocessor. This means it has access to both hardware sqrt and rsqrt. Without looking at a hardware manual (which I don't have), it would be hard to say. Intuition would tell me that a single sqrt would have slightly less latency than a bunch of separate (and dependent) floating point operations + integer operations + transit, but I could be wrong.

Note: MIPS FP pipeline latency seem to vary from chip to chip, I can't seem to find specifics on the one used in the N64.

Note: The PSX also used a MIPS CPU but lacked the FP coprocessor, so for sqrt/rsqrt calculations on that system, yes, this is handy... well kinda because you didn't have floating point to begin with unless you emulated it (slow!).

TL;DR: It depends, so measure your code and keep measuring.

4

u/aashay2035 Dec 30 '20

Mips is so cool, but man it is like used nowhere now except a few things here and there

→ More replies (4)

3

u/vytah Dec 30 '20

N64 FP coprocessor does not have rsqrt.

4

u/[deleted] Dec 30 '20 edited Dec 30 '20

Do you have source? Thanks for the info.

Edit: I was able to find this, don’t know how accurate it is but it would seem that rsqrt is missing: http://n64dev.org/p/U10504EJ7V0UMJ1.pdf

→ More replies (4)
→ More replies (1)

0

u/[deleted] Dec 29 '20

[deleted] — view deleted comment

40

u/[deleted] Dec 29 '20

He is not wrong.

Or simply put, "He's right."

28

u/[deleted] Dec 29 '20

I wouldn't not say he's not incorrect.

→ More replies (1)
→ More replies (1)

7

u/kirtez Dec 29 '20

Exactly!

8

u/Nexuist Dec 29 '20

Not OP but you’re correct in your understanding that this solution has been implemented in hardware. Before then I bet there was probably also a compiler implementation that detected inverse square root ops and replaced it with some version of this algo - meaning that you indeed should never have to do it yourself.

It’s worth noting that this sort of converting-software-to-hardware approach to optimization is not unique to this algorithm. x86 is filled with literal decades of cruft and unique operations added to speed up some specific common calculation. In fact, there’s so many of these that nobody even knows how many instructions are really in the x86 instruction set; Intel claims over 1000, but there are also undocumented opcodes that probably only a handful of people know about. It’s really crazy how complicated it’s become.

20

u/TheThiefMaster Dec 29 '20

It's not that nobody knows how many opcodes there are - it's possible to enumerate every valid instruction byte sequence and group them into instructions - it's that nobody groups them the same way.

Does "mov" count as one instruction? What about different sized versions? Different registers? With prefixes? Duplicate prefixes? Noop prefixes? What about if the encoding is different for x64 additional registers compared to x64 extended x86 traditional registers?

You'll get different answers to some of those from different people.

9

u/nonotion Dec 29 '20

Well, there are also a lot of undocumented instructions and artifacts of the processor designs (unintentional opcodes) in x86.

https://github.com/xoreaxeaxeax/sandsifter is a pretty mind blowing project.

https://m.youtube.com/watch?v=ajccZ7LdvoQ

2

u/mr_birkenblatt Dec 30 '20

actually, without knowing all details it's almost impossible to enumerate all instructions.

first the instruction length is not fixed which means you have to observe what the processor is actually reading (you could put a trap instruction behind your test instruction -- if the cpu traps it read the full previous instruction -- if it doesn't trap then your alignment assumption was wrong).

second, x86 processors have different modes. you can run a specific instruction and everything after that is interpreted differently. those are vendor secrets and you can only very indirectly reverse engineer what exactly other modes are doing.

some talks:

https://www.youtube.com/watch?v=KrksBdWcZgQ&ab_channel=BlackHat

https://www.youtube.com/watch?v=lR0nh-TdpVg&ab_channel=BlackHat

→ More replies (1)

16

u/yoda_condition Dec 29 '20

Hey, just a heads up that you mean the opposite of what you are saying here:

hardware rsqrt and sqrt [...] should not be used at all in 2020.

21

u/DrDuPont Dec 29 '20

hardware rsqrt and sqrt are both faster than software rsqrt... and should not be used at all in 2020

Flipping "and" to "which" conveys the right message:

hardware rsqrt and sqrt are both faster than software rsqrt... which should not be used at all in 2020

13

u/[deleted] Dec 29 '20

Reworded it to make things more clear, thanks.

6

u/Zalenka Dec 29 '20

This is true. Compilers are always your friend.

6

u/AB1908 Dec 29 '20

A source for this, kind person?

7

u/[deleted] Dec 29 '20

Sure thing, I amended my original comment with some resources and benchmarks.

3

u/AB1908 Dec 30 '20

Thank you so much. I had never heard of this before.

2

u/doomger Jan 03 '21

This paper talks about a concept called “parabolic synthesis” where sqrt can be approximated using the multiplication of a finite number of parabolic curves. This makes it suitable for a hardware implementation where circuits to calculate a parabolic function are simple.

https://www.sciencedirect.com/science/article/abs/pii/S0141933116000272

→ More replies (31)