Using keyword argument prevents specialization #45162
Labels
bug
Indicates an unexpected problem or unintended behavior
compiler:lowering
Syntax lowering (compiler front end, 2nd stage)
performance
Must go faster
I raised this issue on discourse, where the consensus seems to be that this is at least very confusing, and possibly a bug.
If I use a kwarg for a function that was passed as an argument to another function, Julia does not specialize the latter function. If I don't use the kwarg for that very same function, it does specialize. Below, I'll include a less trivial example that's closer to my actual use case. But schematically, the idea is this:
Calling, for example,
f2(5, f1)
will result in a specializedf2
; callingf3(5, f1)
will not result in specialization. I imagine Julia is clever enough to optimize the problem away in this schematic. But in my code, I was seeing slowdowns of ~100x and allocations of multiple GiBs on each call to my core computation function.As pointed out in discourse, it's possible to manually trigger specialization by adding a type parameter. But the failure to automatically specialize is a problem for a few reasons:
Core.kwfunc
. So technically the argument "is just passed through to another function" — but not by the programmer. (Gotta love passive voice!)@code_warntype
, JET, Traceur — pointed out any problem with the use of kwargs. In fact, profiling and allocation actively focused my attention on other parts of the code that were not at all the source of the problem. Even the(@which f(...)).specializations
trick from that section of the performance tips seemed to say the function was being specialized for my arguments. (See below.)So, at the very least, I would think this is a documentation bug, because the kwarg wrinkle should be noted in that performance tip — rather than requiring the user to mentally combine disparate arcana from the most cryptic parts of the docs. It would also be nice if some standard tools could point toward the source of the problem. But maybe this is truly a bug in Julia, which should actually specialize even when a kwarg is used?
For reference, here's a working example that's complicated enough that Julia doesn't just optimize the problem away, while still being a greatly simplified version of my actual use case:
And yes, there are plenty of ways to improve the performance of this simplified code with function barriers and such. But my actual code is too complicated for that, with the kwarg func being used multiple times inside some loops.
If I look at the specializations of
inplace!(a, n_max, index)
, I getThat second element really looks to me like it specialized for my particular
index
function.Here's all my versioninfo
The text was updated successfully, but these errors were encountered: