Skip to content

WebGPU target is hitting "error: unknown function: 'isNan'" #10142

Closed

Description

@ScottTodd

Simple e2e repro, and I'm also adding a lit test hitting this in #10134:

iree-compile tests/e2e/xla_ops/minimum.mlir -o /dev/null --iree-input-type=mhlo --iree-hal-target-backends=webgpu
...
Tint reported 1 error(s) for a SPIR-V program, see diagnostics:
error: unknown function: 'isNan'

The compilation flow looks like roughly:

%8 = arith.minf %7, %6 : f32

%6 = arith.cmpf ult, %5, %4 : f32
%7 = arith.select %6, %5, %4 : f32
%8 = arith.cmpf uno, %4, %4 : f32
%9 = arith.select %8, %4, %7 : f32

%8 = spv.FUnordLessThan %7, %5 : f32
%9 = spv.Select %8, %7, %5 : i1, f32
%10 = spv.IsNan %5 : f32
%11 = spv.LogicalOr %10, %10 : i1
%12 = spv.Select %11, %5, %9 : i1, f32

WebGPU removed isInf and isNan back in gpuweb/gpuweb#2311, and Tint removed them in https://dawn.googlesource.com/tint/+/bcd9ad2ebbc183cfbecd75fb6879eb0d55779e5f.

Ideal fixes:

  • Tint could parse spv.IsNan (valid SPIR-V) and generate some polyfilled code in WGSL
    • or WGSL could add back these functions
    • short of those, IREE (spirv dialect?) could add a CleanUpSPIRVForWGSL pass that generates such a polyfill
  • IREE (arith / spirv dialects?) should generate less IsNan and Select code - they shouldn't really be needed for many programs unless the user explicitly asks for them

Activity

  1. added
    bug 🐞
    codegen/spirv
    platform/web 🌐
    on Aug 19, 2022
  2. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    Summarizing some side discussions and reading through the WebGPU history:

    • Some WebGPU backends assume fast-math (including -ffinite-math-only), so including isInf() / isNan() builtins would be misleading. An extension may allow applications to opt-in to stricter checks eventually.
    • Some WebGPU backends may not even support non-finite values, so any polyfill we or Tint can generate could be optimized away or miscompiled
    • Tint accepts the subset of SPIR-V that is translatable to WGSL, so we can't rely on it to implement a polyfill for us here

    So it seems like we're stuck with avoiding spv.IsNan and accepting the -ffast-math tradeoffs. We could run -ffast-math style optimizations (removing NaN checks, etc.) in the spv dialect (or earlier, in arith, if possible), prior to passing SPIR-V to Tint for WGSL translation.

  3. benvanik commented on Aug 22, 2022

    @benvanik
    Collaborator

    Unfortunate that it's not just an optional performance mode :(

    The worst part is going to be when user-provided programs require NANs. In some cases we could try to remove them at a higher level but may still want to error out and require a flag to override - and that's only in cases we could detect - nothing stops a user from passing in NANs as input values at runtime. So sounds like we're going to want to try to find some way of making the common cases of "you tried to use NAN at the input layer but it's not going to work" error out earlier instead of just producing incorrect results. It's never a good practice to rely on NANs but I've seen people use it for errors (since they propagate to outputs and are easy to spot there) and sentinels (end of stream/sequence markers, empty cells in data structures, etc). So long as when users file correctness issues that only show on WebGPU we can easily narrow it down to NANs and point at the best practices/limitations that's probably fine. We should at least stop generating them ourselves (most of them today IIRC) - that's silly.

    Still would be better if this was just an opt-in mode in WGSL. WebGPU is going to be hard for people to target as a general purpose compute API from any frontend (OpenCL/etc) otherwise :/

  4. benvanik commented on Aug 22, 2022

    @benvanik
    Collaborator

    (I'm wondering too if we'd have the same issue on random Vulkan devices even when the compiler access IsNan)

  5. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    Huh, I passed -debug to see where spv.IsNan is introduced in my test (likely in arith/math), but the compiler crashed in the verifier

    // SPIRVOps.cpp
    LogicalResult spirv::GlobalVariableOp::verify() {
      auto storageClass = this->storageClass();
    
    // SPIRVOps.h.inc
          ::mlir::spirv::StorageClass storageClass() {
            return this->type().cast<::mlir::spirv::PointerType>().getStorageClass();
          }
    
    // Types.h
    U Type::cast() const {
      assert(isa<U>());
      return U(impl);

    (more logs and complete callstack: https://gist.github.com/ScottTodd/2b9f15910a1c1b5304ff59c19119eef5)

    Maybe that should be optional? Or I should debug through #10145 first (adding explicit storage classes?)

  6. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    Commenting out the verifier that was crashing, I get debug output that points to CmpFOpNanNonePattern in ArithmeticToSPIRV.cpp as the spot introducing NaN checks for that test.
    (pattern debug output here: https://gist.github.com/ScottTodd/57a13c86ff46ce6383dd98ce0b258f7f)

    So we could either propose an alternate arith -> spv lowering that avoids spirv::IsNanOp or we could add an optional pass that runs later and performs -ffinite-math-only style optimizations in the spirv dialect. Unfortunately, we can't handle this purely in math/arith.

    fyi @antiagainst

  7. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    (And there are likely other places introducing NaNs / NaN checks - that's just one path that I found for a few of our programs and tests. We'll likely need a robust solution for both the intentional NaNs from user code and those that get introduced during regular lowering)

  8. benvanik commented on Aug 22, 2022

    @benvanik
    Collaborator

    I think it's at a higher level - it's the nasty sequence of ordered/unordered compares that get inserted that are the issue (or at least closer to the root).

    For example, %16 = mhlo.compare EQ, %15, %0 : (tensor<5xf32>, tensor<5xf32>) -> tensor<5xi1> (heh extra space) results in an arith.cmpf oeq, which may end up going down to these (it did back in the day, maybe better now).

    Another place is in ArithmeticExpandOps:
    %8 = arith.minf %7, %5 : vector<1x5xf32>
    becomes:

      %8 = arith.cmpf ult, %7, %5 : vector<1x5xf32>
      %9 = arith.select %8, %7, %5 : vector<1x5xi1>, vector<1x5xf32>
      %10 = arith.cmpf uno, %5, %5 : vector<1x5xf32>
      %11 = arith.select %10, %5, %9 : vector<1x5xi1>, vector<1x5xf32>

    Which definitely hits this path.

    min/max kind of stuff is pretty standard in lower levels so I'm surprised we expand it earlier (I see this on the LLVM CPU side too, instead of lowering to llvm.minimum.f32 or the various vector min instructions)

  9. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    Ah, good point. Ideally we'd address this at each level, and generating less comparisons would help across the board.

    FWIW, here's where the CmpFOpNanNonePattern pattern was added: https://reviews.llvm.org/D95237

  10. benvanik commented on Aug 22, 2022

    @benvanik
    Collaborator

    Yeah, that cmp/select/cmp/select dance is really bad as IIRC LLVM/other backends can't/don't practically ever simplify that again while retaining the same semantics. The behavior that nearly everything uses is "return the non-nan value if either value is nan" (GLSL min, OpenCL fminf, C/C++ fminf, CUDA fminf, numpy.fmin, AVX minps, etc), aka "between a NaN and a numeric value, the numeric value is chosen". We need to make sure that if that's the intent of the model (which I hope it is, as it's the only thing that makes sense) we can propagate that all the way to backends. There's some ISAs that do weird things but it'd be better to pay the cost there rather than everywhere like we do today.

  11. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    Cool! I got some promising results by just commenting out

    pm.addNestedPass<func::FuncOp>(arith::createArithmeticExpandOpsPass());

    image

    my is_nan.mlir test that uses arith.minf still fails at

    Tint reported 1 error(s) for a SPIR-V program, see diagnostics:
    error: cannot initialize let of type 'ptr<storage, f32, read>' with value of type 'ptr<storage, f32, read_write>'
    

    but that's tracked in #10145

  12. benvanik commented on Aug 22, 2022

    @benvanik
    Collaborator

    We add that pass on all backends and I'm not sure we should - would be good to get a codegen person to look into it.

  13. ScottTodd commented on Aug 22, 2022

    @ScottTodd
    MemberAuthor

    We add that pass on all backends and I'm not sure we should - would be good to get a codegen person to look into it.

    Ah, createArithmeticExpandOpsPass came from an LLVM integrate (back with the old process where people outside our team did those for us :P): f7a3c8c. Definitely worth a closer look from someone more familiar with codegen. I can also try removing it to see what breaks.

  14. antiagainst commented on Aug 22, 2022

    @antiagainst
    Member

    Great digging, Scott!!

    • Some WebGPU backends may not even support non-finite values, so any polyfill we or Tint can generate could be optimized away or miscompiled

    I'm actually wondering how popular / recent this is. I feel the shader compilation side tends to cater to very old hardware / compiler flows (or even bugs!) for a long time; so we always have those historical baggages lingered on for a long time. Given WebGPU / WGSL is something new; it would actually be good to look it more closely to see how things stands today. But I don't have data points / experience with this directly. So just my two cents. :)

    Anyway, in addition to clean up our own pipeline to avoid generating those NaN checks, I think it makes sense to throw in a pattern to polyfill OpIsNan by ourselves given that WGSL / Tint believes it's not their responsibility and it should be done by the SPIR-V producer, for the cases as Ben mentioned where we do needs such NaN checking as part of the original input's logic. (Conceptually this is like "legalizing the SPIR-V" for the "target environment of WGLSL".)

    (I'm wondering too if we'd have the same issue on random Vulkan devices even when the compiler access IsNan)

    From the spec actually the default mode is also assuming no inf/NaN/-0, etc., though we have a way to control that. I don't see issues w.r.t. NaN thus far on any hardware/architecture; so I guess it's fine.

  15. added a commit that references this issue on Aug 30, 2022
  16. moved this to In Progress in IREEon Sep 28, 2022
  17. ScottTodd commented on Oct 3, 2022

    @ScottTodd
    MemberAuthor

    This is mostly fixed with #10352, but we won't be able to support programs that depend on NaN/Inf until WebGPU / WGSL add support for them (gpuweb/gpuweb#3424, and related discussions).

  18. Repository owner moved this from In Progress to Done in IREEon Oct 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug 🐞codegen/spirvplatform/web 🌐

Type

No type

Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions