You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
WebGPU target is hitting "error: unknown function: 'isNan'" #10142
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
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.
The GPU behavior in this case is subject to the accuracy of the GPU hardware implementation of the IEEE-754 standard.
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.
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 :/
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.
(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)
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:
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)
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.
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>'
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.
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.
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).
Activity
ScottTodd commentedon Aug 22, 2022
Summarizing some side discussions and reading through the WebGPU history:
-ffinite-math-only), so includingisInf()/isNan()builtins would be misleading. An extension may allow applications to opt-in to stricter checks eventually.So it seems like we're stuck with avoiding
spv.IsNanand accepting the-ffast-mathtradeoffs. We could run-ffast-mathstyle optimizations (removing NaN checks, etc.) in thespvdialect (or earlier, inarith, if possible), prior to passing SPIR-V to Tint for WGSL translation.benvanik commentedon Aug 22, 2022
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 :/
benvanik commentedon Aug 22, 2022
(I'm wondering too if we'd have the same issue on random Vulkan devices even when the compiler access IsNan)
ScottTodd commentedon Aug 22, 2022
Huh, I passed
-debugto see wherespv.IsNanis introduced in my test (likely in arith/math), but the compiler crashed in the verifier(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?)
ScottTodd commentedon Aug 22, 2022
Commenting out the verifier that was crashing, I get debug output that points to
CmpFOpNanNonePatterninArithmeticToSPIRV.cppas 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->spvlowering that avoidsspirv::IsNanOpor we could add an optional pass that runs later and performs-ffinite-math-onlystyle optimizations in the spirv dialect. Unfortunately, we can't handle this purely inmath/arith.fyi @antiagainst
ScottTodd commentedon Aug 22, 2022
(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)
benvanik commentedon Aug 22, 2022
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 anarith.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:
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.f32or the various vector min instructions)ScottTodd commentedon Aug 22, 2022
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
CmpFOpNanNonePatternpattern was added: https://reviews.llvm.org/D95237benvanik commentedon Aug 22, 2022
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.
ScottTodd commentedon Aug 22, 2022
Cool! I got some promising results by just commenting out
iree/compiler/src/iree/compiler/Codegen/SPIRV/Passes.cpp
Line 157 in d4ba930
my
is_nan.mlirtest that usesarith.minfstill fails atbut that's tracked in #10145
benvanik commentedon Aug 22, 2022
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.
ScottTodd commentedon Aug 22, 2022
Ah,
createArithmeticExpandOpsPasscame 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.antiagainst commentedon Aug 22, 2022
Great digging, Scott!!
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
OpIsNanby 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".)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.
Remove ArithmeticExpandOpsPass from SPIRV and VMVX lowerings. (#10162)
Squashed commit of the following:
[spirv] Add fast math support for WebGPU (#10352)
ScottTodd commentedon Oct 3, 2022
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).
Bump Tint, spirv_headers, and spirv-tools to latest. (#11318)