An adventure in trying to optimize math.Atan2 with Go assembly
agniva.me
agniva.me
[1] http://www.embedded.com/design/other/4216719/Performing-effi...
[2] https://stackoverflow.com/questions/6118028/fast-hyperbolic-...
Looks like f(x)=x+x^3/5 gets you two decimal digits everywhere [1], and you could improve that with more terms in the polynomial.
Edit: you can derive f(x) by doing a series expansion of tanh(x)/√(1-tanh(x)²) about x=0, and Mathematica tells me the first few terms are
f(x) = x + x^3/6 + x^5/120 + x^7/5040 + O(x^9)
And yes, the Taylor series is pretty good but you can usually squeeze a bit more accuracy-over-range by, eg, using an optimizer for the coefficients. Also, note that in your notebook you have x^3/5 but x^3/6 is probably what you wanted.
> Avoid special cases, because a special case means slow code
So yeah, handling of special cases will bite you on the performance side. Sometimes it's inevitable, but if you have a lot of control (or you're very specific) of what values get passed as parameters, then you can get away with not handling special cases (or just handling the ones you care about).
[1] http://www.java-gaming.org/topics/extremely-fast-atan2/36467...
Its a flight tracking algorithm which calculates velocity of the aircraft from the messages it broadcasts.
EDIT: > then it's likely that what you are doing could be done with some regular vector manipulation (normalisation, possibly dot product, cross product).
Yes, totally. Like I said, I have zero knowledge in assembly. And what you are talking about "vector manipulation" is totally beyond me ;) Just doing this part took a lot from me. :D
Maybe someone knowledgeable enough will be kind enough to write an improved implementation.
C4 - For a three-byte instruction (which vfmadd is) this is C4, if a two-byte instruction this would be C5.
E2 - This one is more involved but basically for this instruction the first three bits are 1 for setting some modes on it (R, X, and B). Then, because this is an 0f38H instruction, the next 5 bits are 00010. Altogether you get 11100010 (E2)
E9 - this is also involved, but the first bit is a W mode. This is 1 for the instruction he used but it's pretty much ignorable. for bits 2-5 it has to do with the first source register the instruction uses. This is 1101 because it uses XMM2/YMM2 (it's by lookup in a table) first. bit 6 is set to 0 if it is a 128 bit vector (it is). bit 7-8 are set to 01 based on a lookup table for the "pp" value which is 66 in the instruction identifier. Altogether that's 11101001 (E9).
A8 - this one is easy, it's the opcode.
C3 - this is the ModR/M byte which is actually used in this case for reporting the register/memory operands. first 2 bits are 11 to indicate the first operand is the register itself (not displaced, or truncated). The next 6 bytes are the register codes. 000 is actually not used since the destination is overriden for float maths), and the 011 is EBX as the base cpu register to source the data.
Altogether it works out to be C4E2E9A8C3. Not intuitive at all really.
Edit: Please someone correct me if I missed something. I hate this kind of stuff and I'm sure I made a mistake.
He should take a look at:
a) the range of x which will be used for atan2(x)
b) the level of precision he really needs
There is a chance he could get away with precomputing an atan2(x) table in memory and then just reading the values off the table.
Quick as lightning, and an old trick, probably invented in the 1950s!!
EDIT: I see i am potentially wrong, due to slower DRAM access compared to some built-in FP instructions...
I learnt a new slang today, thanks!
Yes, linear interpolation is a possibility. Another could be to use a quadratic (or nth-order) function f that approximates atan2(x) when x is within the range you need, so that you get a really good approximation with a quick and dirty computing.
In particular, if your equation uses powers of 2 and 4, the power operation perhaps can be done by bit shifting which is blazingly fasssssssssst.
I had to google it to see what "lerping" was supposed to mean, and the whole experience was too disappointing. The lerping and tweening slang appears to be a reinvention of basic concepts (parametrization) derived from ignorance and poor math literacy. It appears that some people failed to pay attention to intro to calculus courses and decided to just come up with new names for tired old concepts.
I actually tried this for cos and sin lookups, and lerping between datapoints.
It was actually slower than the builtins!
Not just potentially. See this: https://github.com/Const-me/LookupTables
The first critical failure is using the source code to guide assembly optimization, rather than the original generated assembly. It means that you're going to miss what optimizations the compiler is doing to improve this, and missing those optimizations is going to turn out worse than the original.
There are two main optimizations that come to mind. The first is instruction scheduling. On newer CPUs (Haswell or later), you have two separate instruction ports for vector ALU instructions, so you can execute two instructions in parallel if there are no conflicts. If you interleave the instructions for computing the denominator and the numerator, you can take advantage of the twin execution ports and execute two instructions at once instead of two (you use more registers though). This is the main optimization that I'm sure the Go library is getting.
The other possible optimization is SLP vectorization: the numerators and denominators are both polynomial interpolation, so they're doing the same operations on data vectors. This means that you can stick both of them in the vector and use one instruction to compute the operation for numerator and denominator simultaneously. On the other hand, it's not immediately clear if the extra cost in vector formation is going to be worth the win in speed, particularly given that you can already simultaneously schedule the two instructions in the first operation. I don't know if Go is applying this optimization.
So if you're wondering why it's slower, it's almost certainly that the hand-written assembly is actually poorly scheduled.
The assembly is slower because Go doesn't inline it. The overhead is obvious when calling one-op assembly blocks[1]. The proposal to inline assembly was rejected last year[2] by Russ Cox.
[1] https://lemire.me/blog/2016/12/21/performance-overhead-when-...
Yes I realized ! Expert ? Not even close. I barely know a thing or two in assembly. The fact that I even managed to make it run amazes me.
This was my first time venturing into the assembly land. It was just something which I wanted to give a shot and hopefully learn something at the end of the day, which I did.
The 2 optimizations that you are talking about - I am totally clueless about them :) It's totally possible that if whatever you are saying is done, we may see better gains. Hopefully, some good samaritan who is better at this than me will be willing to give this a shot and see where it gets us.
Shouldn't something like this be implemented as a hardware level operation? Or is it? Or why can't it be? Or maybe it's not used nearly as much as I think?
DRAM read takes ~210 cycles (assuming 60ns access time and 3.5 GHz CPU clock rate).
FPATAN takes ~50 to 200 cycles, depending on the operand value and CPU model (see http://www.agner.org/optimize/instruction_tables.pdf)
I suspect a polynomial approximation takes less than either of these, since that's what most C standard library implementations use on the PC (I just check Visual Studio 2017).
It's probably the slowest way the first time, but if you call atan2 in a loop, won't it be much faster?
Each time the table access hits a new cache line, there will be a stall. Say your LUT has 2048 64-bit entries, that's 256 cache lines. So the total stall time waiting for cache lines to be filled could be as bad as 210 cycles * 256 = 53760 cycles. In that amount of time, the std library function could have returned about 1000 results (assuming the std library takes 50 cycles).
And, as well as waiting for the table reads, the LUT based function has other work to do. If we are comparing performance to the std library function, it handles input from the entire range of IEEE 64-bit floats. It isn't practical to do that directly with a lookup table. You would need to clamp the range down to something manageable. Once that's done, if you want anything like decent accuracy you need to read two values from the table and do a linear interpolation between them. Or you could have a HUGE table instead of the lerp but it would have to be far too big to fit in L1 cache, and thus also quite slow.
My guess is a clamp and lerp'd lookup table will take ~10 cycles once the table is entirely in cache. So, I guess I'm claiming that the LUT would then be 5x faster than the std library.
I don't have a lot of confidence in that prediction though. There are lots of other things to worry about if we were to do this analysis properly, including: a) how the input pattern alters the effectiveness of the branch predictor, b) how exactly you are finding some input data to operate on without polluting the cache, c) whether we are measuring latency or throughput.
https://github.com/golang/go/issues/17069#issuecomment-24637...
(Everyone in the company who could hand-code (even us OS guys and gals ;-) was assigned a math routine--it was an all-hands-on-deck kind of performance situation in our competition with Alliant and Convex.)
Imagine trying to hand-schedule up to 28 operations at once, including all memory loads with 12 or 14 (forget now) clocks to memory, all bus contending had to be done by hand, etc, etc. What fun! That's why VLIW compilers were so challenging to write: all resources software-managed.
But, alas, in the end the mini-super market died. We all lost to Sun eventually, as everyone wanted his own machine, even if much less powerful--never bet against having the computer power closer to the user (starting with mainframes): minicomputer / workstation / PC / mobile / etc, right down the line to today.
(What's going to displace mobile, IoT? Doesn't seem likely. Perhaps when you reach the limit of what you can hold in your hand, that's the last form factor? I don't believe wearable computing will ever really catch on, but I'm old fustian.)
I used to think the same, but it seems to me that phones are the first step. A huge number of people have a mini computer on their persons all day. It's only a matter of time before it becomes even more integrated.
Will be interesting to see, but I doubt the current form factors will win. Smart watches seem so... not it.
But yea, knowledge is knowledge.
Thanks for posting this.
* math.Atan2 is in the standard library, so it should know it has no side effects and can be replaced with an empty statement. Unless Go has a way to mark a function as not having side effects, no user-defined function would have that property.
* The only observable impact of the loop if math.Atan2 is removed is that b.N could be a larger size type than n, so it could loop forever depending on the values. If they're known to be the same type, it could eliminate the loop entirely.
Are you sure you're compiling with optimizations enabled?
I also wonder if that DIVSD instruction in yours might cause a floating point exception, which would be a different behavior compared to atan2.
When writing benchmarks in Go you always need to take steps to circumvent the optimizer detecting functions with no side effects. Assigning the result of a benchmark to a public package level variable is usually enough.
> I'm surprised it doesn't eliminate the BenchmarkAtan2 entirely:
I'm sorry, could you clarify what you mean by "eliminate" here. Are you saying I shouldn't benchmark atan2 but something else ?
> Are you sure you're compiling with optimizations enabled?
I just did - `go test -bench=. -benchmem -cpu=1`. Did I miss something ?
> I also wonder if that DIVSD instruction in yours might cause a floating point exception, which would be a different behavior compared to atan2.
I checked with the assembly output of math.Atan2. It also uses DIVSD.
He's talking about a common compiler optimization: https://en.wikipedia.org/wiki/Dead_code_elimination
Some compilers are smart enough to not run code that doesn't have any side effects. (Running a function a million times in a row but never doing anything with the results)
Hopefully golang bench is smart enough to not be that smart.
> Hopefully golang bench is smart enough to not be that smart.
Yes, that seems to be true.
Most compilers will eliminate code if they can tell the results of a calculation are never used. Benchmarks typically call some function and discard the result. If you aren't careful, the compiler can often optimize away your entire benchmark down to nothing.
This is why you often see benchmarks that look like:
int average(a, b) {
return (a + b) / 2;
}
main() {
int sum;
for (int i = 0; i < 100000; i++) {
for (int j = 0; j < 100000; j++) {
sum += average(i, j);
}
}
if (sum != 123) printf("!");
}
Instead of: int average(a, b) {
return (a + b) / 2;
}
main() {
for (int i = 0; i < 100000; i++) {
for (int j = 0; j < 100000; j++) {
average(i, j);
}
}
}Yes, it seems Go is smart enough not to eliminate those values entirely.
I think this might be a better way to be sure that the function will be computed entirely.
`_ = myatan2(-479, 123)`
The result is same though. I will update the post.
z := x * x
z = z * fma(fma(fma(fma(P0, z, P1), z, P2), z, P3), z, P4) / fma(fma(fma(fma((z+Q0), z, Q1), z, Q2), z, Q3), z, Q4)
z = fma(x,z,x)
This article is quite the nerd-snipe.
Alternatively, set `#pragma STDC FP_CONTRACT ON` and just write `x*y + z`.