‹ BackHN Continuity

Thread

Fearless SIMD v1.0

318 points · 52 comments · verdagon

  1. modulovalue · · focus · HN ↗
    I’m currently working on adding better SIMD support to Dart (<a href="https:&#x2F;&#x2F;github.com&#x2F;dart-lang&#x2F;sdk&#x2F;issues&#x2F;64170" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;dart-lang&#x2F;sdk&#x2F;issues&#x2F;64170) and I have a question for the author or others here.

    Does Rust or any other language support customizing the compiler so that interprocedural analyses can track custom subsets of, for example, doubles so that the compiler can choose the most efficient instruction sequence for example for min&#x2F;max? If we know a double is never NaN then we can emit only one instruction on x86, but have to emit one more on arm64. If we know a double is never zero and never NaN, we can emit a single instruction on both.

    This whole conversation between relaxed SIMD and deterministic SIMD seems to only exist because our compilers are not smart enough and&#x2F;or their whole program analyses don’t support any plugin-like capabilities.

    There are other examples where if we know a SIMD bitmask is canonical (all 1s per lane) then we can implement horizontal reductions more efficiently. This is very niche and I doubt that any language supports interprocedural analyses with such a rich domain, so it feels like a hole in the programming language space.

    1. athrowaway3z · · focus · HN ↗
      Last time i checked; no.

      But I suspect you&#x27;re overvaluing the potential savings. Knowing when a float is 0.0 or NaN beforehand is almost entirely impossible, except for the most trivial of cases - like when you first initialize a variable or first enter a loop. Everything after that is very hard or impossible with floats as they are.

      Those cases can be const folded at compile time.

      Those cases are never a measurable bottleneck.

      The closest thing I know of in the realm of the optimization you&#x27;re curious about is Rust NonZero* variants, but they&#x27;re used for enum compression afaik.

      1. modulovalue · · focus · HN ↗
        I’m not sure I agree on the impossible part, I feel like a sufficiently smart interprocedural analysis that also implements range analysis interprocedurally could prove a lot to where it becomes useful.

        I guess what I would like to see is SIMD libraries being able to confidently say nobody needs to use intrinsics (or differentiate between relaxed&#x2F;normal SIMD on the user API level) because the language + high level SIMD APIs are smart enough to choose the right implementation.

        IIRC IEEE min&#x2F;max with proper NaN handling needs 8 instructions on x86 vs 1 on arm64 I find it very sad that we apparently haven’t really solved that yet without forcing the user to use different APIs.

        1. orlp · · focus · HN ↗
          You can do it with just 3 instructions for IEEE 754-2019 minimumNumber (ignores NaN):

                  vminpd          ymm2, ymm1, ymm0
                  vcmpunordpd     ymm0, ymm0, ymm0
                  vblendvpd       ymm0, ymm2, ymm1, ymm0
          
          If you want proper IEEE 754-2019 minimum (propagate NaN, -0.0 &lt; +0.0, NaN bitpattern picked in the usual way) you can do it in 6:

                  vminpd          ymm1, ymm0, ymm1
                  vbroadcastsd    ymm2, qword ptr [rip + .LCPI0_0]
                  vandpd          ymm2, ymm0, ymm2
                  vorpd           ymm1, ymm2, ymm1
                  vcmpunordpd     ymm2, ymm0, ymm0
                  vblendvpd       ymm0, ymm1, ymm0, ymm2
          
          I personally find this a load of nonsense I don&#x27;t care about.

          If you want propagating NaNs but don&#x27;t care about signed zero or NaN payload&#x2F;sign, you can use

                  vminpd  ymm2, ymm0, ymm1
                  vminpd  ymm1, ymm1, ymm0
                  vorpd   ymm0, ymm1, ymm2
          
          What I do in Polars is a bit different, there for propagating NaNs I do

              if (self &lt; other) | self.is_nan() { self } else { other}
          
          this isn&#x27;t fully optimal on x86-64 but it&#x27;s fairly simple and autovectorizes decently on various platforms, here&#x27;s AVX2:

                  vcmpltpd        ymm2, ymm0, ymm1
                  vcmpunordpd     ymm3, ymm0, ymm0
                  vorpd           ymm2, ymm3, ymm2
                  vblendvpd       ymm0, ymm1, ymm0, ymm2
          1. dzaima · · focus · HN ↗
            That vminpd+vminpd+vorpd actually does handle signed zero properly! Screws up NaN payloads to the max though. Can be easily extended to canonicalize the NaN with 2 instrs + constant though of course. (which ends up at the same number of instrs as your proper impl (albeit with worse port distribution and latency), but you get to have a canonical NaN!)

            Hit upon <a href="https:&#x2F;&#x2F;github.com&#x2F;llvm&#x2F;llvm-project&#x2F;issues&#x2F;217376" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;llvm&#x2F;llvm-project&#x2F;issues&#x2F;217376 while playing around with proper minimumnum, failing to SMT-verify whatever version of LLVM I had; did find a funky working 6-instr (+ constant) version though:

                vpandn      ymm2, ymm1, ymm0
                vpcmpeqd    ymm2, ymm2, 0x80000000 # whether ymm0 is -0 and ymm1 is +0 (or other cases that magically don&#x27;t cause issues)
                vcmpltpd    ymm3, ymm0, ymm1
                vcmpunordpd ymm3, ymm3, ymm1 # regular NaN-is-larger ymm0&lt;ymm1
                vpor        ymm2, ymm2, ymm3
                vpblendvb   ymm0, ymm1, ymm0, ymm2
            1. [deleted] · · focus · HN ↗

              [deleted]

            2. dzaima · · focus · HN ↗
              Stop the presses! 5 instructions!

                  vpor        xmm2, xmm0, 0x80000000
                  vpcmpeqd    xmm2, xmm1, xmm2
                  vcmpunordps xmm2, xmm2, xmm0
                  vminps      xmm0, xmm1, xmm0
                  vblendvps   xmm0, xmm0, xmm1, xmm2
              
              yay for superoptimizers
        2. athrowaway3z · · focus · HN ↗
          Anything without range analysis is not worth it.

          Note that:

          NonZerof32 * NonZerof32 -&gt; NonNanf32

          NonZerof32::from_bits(1) multiplied with itself is zero.

          Doing range analysis needs the language to support it at compile time, and the dev to specify what range it is.

          The only &#x27;stable&#x27; thing i can think of is a type for &#x27;greater-eq-one&#x27; using only addition and multiplication. Practically every other operation breaks most of the type knowledge up to that point.

        3. nnevatie · · focus · HN ↗
          &gt; nobody needs to use intrinsics

          Funnily enough, intrinsics have become almost trivial to write, with agentic tooling. I used to be an ISPC advocate but now I&#x27;m finding myself gravitate to direct use of intrinsics with bespoke dynamic&#x2F;runtime dispatching more than ever.

          1. janwas · · focus · HN ↗
            +1 on agents making library&#x2F;DIY a lot more attractive than bespoke compilers.

            In C++, one can also have portable intrinsics plus simpler runtime dispatching using our Highway library :)

            1. nnevatie · · focus · HN ↗
              &gt; using our Highway library

              Yes, Highway is pretty nice but also quite elaborate when it comes to dealing with multiple vectorized versions and dispatch. The macros burn my eyes still.

              1. janwas · · focus · HN ↗
                :) Yeah, those are best copy-pasted from existing code.

                I do think we&#x27;ve converged on the best that&#x27;s possible in C++.

    2. VorpalWay · · focus · HN ↗
      Not yet that I know of, though perhaps LLVM might be able to infer simple cases (when loading from a known constant for example).

      Pattern types could potentially maybe in the future allow for the compiler to know more details though. They are a nightly feature, and afaik only for enums, integers and pointers so far. The idea would be that you can define a custom type such as &quot;an integer between 7 and 45&quot; and everything else become niches for niche optimisation (e.g. for `Option&lt;MyFunkyInt&gt;` some of those impossible values would be used to represent the None case of the wrapping Option).

      But I could envisage a future in which you could say &quot;f64 without NaN&quot; which would both make those available for niches and potentially tell LLVM about this. However, we are very far from any of that currently. And it might not be what you want, since you would need to add checks when you perform operations to ensure the value doesn&#x27;t suddenly become a NaN. Which is way more complicated than ensuring integers don&#x27;t become, say, zero. It will likely be much harder to optimise away the checks.

      1. modulovalue · · focus · HN ↗
        &gt; Pattern types could potentially maybe in the future allow for the compiler to know more details though.

        Thanks, I’ll take a look!

        1. VorpalWay · · focus · HN ↗
          That is a big maybe though. It is very experimental (didn&#x27;t even have non-placeholder syntax last I looked), and as far as I know nobody has yet even discussed it for floats.
      2. borodi · · focus · HN ↗
        LLVM has range flags and things like nnan that could in theory be used to replace a minimum intrinsic into a minimumnum (iirc x86 has a instruction for the latter but not the former) <a href="https:&#x2F;&#x2F;llvm.org&#x2F;docs&#x2F;LangRef.html#floating-point-min-max-intrinsics-comparison" rel="nofollow">https:&#x2F;&#x2F;llvm.org&#x2F;docs&#x2F;LangRef.html#floating-point-min-max-in... I&#x27;m not sure if the optimizations use this but in theory they could
      3. 0xdeafbeef · · focus · HN ↗
        Sounds similar to <a href="https:&#x2F;&#x2F;mlir.llvm.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;mlir.llvm.org&#x2F;
    3. JonChesterfield · · focus · HN ↗
      Customized compiler isn&#x27;t really a thing in most languages. Because it implies changing the language, and everyone agreeing on what the language is was sort of the point of the whole exercise. Hence all the worries about macros.

      SBCL has the right hooks. Jai probably does as well. You could build your own thing on LLVM relatively easily - so Rust _could_ do it if you gave it sufficient access to the compiler, but so could C++ or D.

      SIMD bitmasks being ~0 instead of (00000001)+ is common and useful, but there&#x27;s an annoying language design question in there about what type comparisons between vectors should be (if you don&#x27;t have a &lt;N x i1&gt; as a type, say because you liked C too much). Shout out to std::vector&lt;bool&gt;.

      There is probably interesting work in mojo for this. The library being in MLIR strongly encourages taking that sort of approach. I haven&#x27;t looked at their implementation though. Happy hacking!

      1. adgjlsfhk1 · · focus · HN ↗
        Julia also does this quite often (both using macros to write DSLs or minor modifications, and packages like GPU backends that hook the compiler functionality to compile direct GPU assembly kernels.
    4. adastra22 · · focus · HN ↗
      I think you are looking for NotNan&lt;f64&gt; from ordered-float crate?
    5. Archit3ch · · focus · HN ↗
      Possible in Julia without patching the compiler with a compiler extension package.
    6. barchar · · focus · HN ↗
      LLVM does do bit pattern tracking. Referred to as value tracking or known bits analysis.

      I’m not sure if the vectorizer uses it a ton, but isel does (though maybe not heavily for vector ops)

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.