Skip to content

Out-of-bounds behavior in shaders #35

Closed

Description

@litherum

We all agree that some form of out-of-bounds checking needs to happen at runtime. From our discussion two weeks ago, we came up with two forms of this checking:

  1. Clamping, where array indices which have a too-high index automatically access the last value of the array
  2. Trapping, where such access causes the shader stage to immediately end, feeding zeroes to all pipeline stage output variables.

In Metal, option 1 looks like this:

data[clamp(index, 0U, dataCount)]

and option 2 looks like this:

if (index > dataCount) {
    Output output;
    // Fill in the fields of "output" with zeroes
    return output;
}
data[index];

I did some performance testing in Metal on "iPad mini with Retina display" to try to evaluate these two techniques. There are three styles of performance tests:

Tight Loop

In Metal, this code looks like:

device float* data [[ buffer(1) ]]; // Buffer the user-authored shader wants to read from
device uint32_t& dataCount [[ buffer(2) ]]; // Implicit buffer, which contains the length of "data"
...
VertexOutput output;
float sum = 0;
for (uint32_t i = 0; i < 100000; ++i) {
    sum += data[clamp(i, 0U, dataCount)];
}
output.position = [some function of "sum"];
return output

Here are the performance results. All times are in ms.

  Tight Loop Unchecked Tight Loop Clamp Tight Loop Trap
1000 items 5.26997131676063 5.68129132211016 5.52152075518696
3000 items 5.51838883162774 6.51381429188452 6.33112298559014
10000 items 6.21394229649268 9.44977917071966 8.00736172385653
100000 items 12.9947847222175 35.1627072386362 30.8669331404834

Totally Inlined Loop

In Metal, this code looks like:

device float* data [[ buffer(1) ]]; // Buffer the user-authored shader wants to read from
device uint32_t& dataCount [[ buffer(2) ]]; // Implicit buffer, which contains the length of "data"
...
VertexOutput output;
float sum = 0;
sum += data[clamp(0U, 0U, dataCount)];
sum += data[clamp(1U, 0U, dataCount)];
sum += data[clamp(2U, 0U, dataCount)];
...
output.position = [some function of "sum"];
return output

Here are the performance results. All times are in ms. Note that, for larger programs, the runtime compiler times out and doesn't emit code, so I couldn't test them.

  Inlined Unchecked Inlined Clamp Inlined Trap
1000 items 5.39240562908213 6.14405965171417 5.3955658573221
3000 items 5.65435510235397 8.08545490402 5.64488865150129
10000 items - - -
100000 items - - -

Partially Inlined Loop (chunk size = 100)

In Metal, this code looks like:

device float* data [[ buffer(1) ]]; // Buffer the user-authored shader wants to read from
device uint32_t& dataCount [[ buffer(2) ]]; // Implicit buffer, which contains the length of "data"
...
VertexOutput output;
float sum = 0;
uint32_t index = 0;
for (uint32_t i = 0; i < 100000 / 100; ++i) {
    index = i * 100 + 0; sum += data[clamp(index, 0U, dataCount)];
    index = i * 100 + 1; sum += data[clamp(index, 0U, dataCount)];
    index = i * 100 + 2; sum += data[clamp(index, 0U, dataCount)];
    ...
    index = i * 100 + 99; sum += data[clamp(index, 0U, dataCount)];
}
output.position = [some function of "sum"];
return output

Here are the performance results. All times are in ms.

  Partially Inlined Unchecked (Chunk = 100) Partially Inlined Clamp (Chunk = 100) Partially Inlined Trap (Chunk = 100)
1000 items 5.29934397381731 5.95148991506805 5.73344740079656
3000 items 5.45856812753239 7.18951789342246 6.69228472859371
10000 items 5.95523161258487 11.658497685183 10.0505332602401
100000 items 12.3861319985335 51.63057076149 39.1050798693512

Activity

  1. dneto0 commented on Oct 25, 2017

    @dneto0
    Contributor

    Thanks for gathering these data.

    Your test cases so far don't have any function calls. The overhead of option 2 increases when the emulated-trap occurs deeper in a call stack. In such a situation the error condition must bubble up and be propagated through all the call sites.

    Yes, in principle a shader should always be inlinable, and full inlining avoids this extra overhead. However, for some applications full or significant inlining produces extremely undesirable blowup in shader size (either before or after it's handed to the implementation). So we should account for the non-inlined case to get a complete picture of the costs.

  2. kainino0x commented on Oct 26, 2017

    @kainino0x
    Contributor

    data[clamp(index, 0U, dataCount)]

    Since index is unsigned, it could be faster to usedata[min(index, dataCount)]. The compiler may be able to optimize this but it's worth making it as similar to the trap example as possible.

  3. dmikis commented on Oct 26, 2017

    @dmikis

    @litherum, thanks for quantifying a tricky discussion. I'd like them to go more in that direction.

    However, It'd be interesting to see how these measurements fluctuate. Your results are quite close so, as I've said on the call, maybe there's no actual difference.

  4. devshgraphicsprogramming commented on Nov 14, 2018

    @devshgraphicsprogramming

    OpenGL's ARB_robustness regulates some of these issues, I suggest you adopt its conventions #33 .

    This is because on some platforms and drivers you may actually rely on ARB_robustness doing its job and the "software" (added) clamping/trapping will not be necessary.

  5. devshgraphicsprogramming commented on Nov 16, 2018

    @devshgraphicsprogramming

    Also in Vulkan you could only support backends in MVP that have VkPhysicalDeviceFeatures.robustBufferAccess

    P.S. You may not actually see that much of a performance hit between Unchecked vs {Clamp/Trap} in actual use-cases where there is more data than fits in your L1 for all shader invocations, and it is fetched from buffers.
    Even on high-end Nvidia GPUs, global memory access is like a 1000 cycle latency.

  6. kvark commented on Nov 20, 2018

    @kvark
    Contributor

    @devshgraphicsprogramming

    Also in Vulkan you could only support backends in MVP that have VkPhysicalDeviceFeatures.robustBufferAccess

    The group is concerned about portability of programs that attempt to access outside of the bounds. It's not OK if the program works on one machine and doesn't work on another, and we don't detect it and should loudly. The GL/Vk robust buffer access gives the driver quite a bit of leeway on how it can behave, which can be the source trouble. These benchmarks are trying to answer the question of how much we'd lose in terms of performance if we just enforce a particular behavior on our side.

  7. devshgraphicsprogramming commented on Nov 20, 2018

    @devshgraphicsprogramming

    Why would you care about the portability of ill-behaved (such which access outside the bounds) programs?

    Its the job of validation layers (which do not have to be enabled or attached in production) in the next-gen APIs to do the detection and shouting.

    I.e. some compilers can already tell you and refuse to compile compute shaders where you'd access out-of-bound shared memory with an index.

  8. kainino0x commented on Nov 20, 2018

    @kainino0x
    Contributor

    If a developer can't tell whether their application is ill-behaved, then they're going to write it anyway. Those applications are going to be written on one machine, tested on two or three, and run on thousands - so they need to behave similarly. (Or we need to detect ill-behaved programs in a platform-independent way. We should always do this when it's possible.)

    And once you've made programs that are "ill-behaved but not in a detectable way" run consistently, there's no reason to consider them ill-behaved. So some of these "ill-behaved" programs are really well-behaved programs, with reproducible behavior.

    Of course, there are performance tradeoffs. We want to do this where the performance is not significantly worse than what we absolutely have to do for security anyway.

  9. devshgraphicsprogramming commented on Nov 21, 2018

    @devshgraphicsprogramming

    Or we need to detect ill-behaved programs in a platform-independent way. We should always do this when it's possible.

    I'm entirely for this, but this needs to be an optional thing that is only enabled when a bug-report/profile is to be submitted.
    A validation layer like that would reduce performance 4x or even 100x if you really want to nail down the all the ways to misuse the API.

    And such a validation layer would have to be developed and maintained by the same organisation that maintains and develops the API spec + conformance tests. After all, the validation itself must be portable.

    By specifying a fat OpenGL-like-API that attempts to fight all the corner cases and not let the user fail, you not get rid of portability issues. Unless you are aiming to provide reference implementation for every OS that the browsers will use, the portability concern will simply shift from you to the browser API implementers, and we all know how they tend to have portability issues even with the simplest features.
    What I anticipate that us, the end users, will end up with an API that is de-jure portable and you with a clean conscience, while the de-facto will be that programs will not be portable because of browser bugs or misreading of the spec by implementers or insufficient resources dedicated to the implementation or worse native-API driver issues.

    Despite best efforts from other web-APIs people still need to test:
    https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction

    Take this example of a failed webGL implementation on a D3D backend (same browser, different OS, different native API backend):
    https://stackoverflow.com/questions/37617789/three-js-shader-error-on-different-computers-same-browser/37617896
    mrdoob/three.js#8161

    P.S. In my experience I would rather have a harder to use but simpler to implement API, then at least the bugs I encounter will be mostly my fault and can be fixed by me. On the other hand with API implementation bugs (such as the ever present issues in Intel OpenGL Windows drivers) are near impossible for me to correct-for, leave me stranded (I cannot force the browser team to quickly fix the implementation issue and release an update ahead of their planned schedules) and require me to write platform-specific performance-reducing workarounds.
    For example, NVIDIA never reads or responds to the bug reports about their Linux OpenGL driver even when supplied by their chosen and preferred routes with supplementary minimal-reproducible examples and API-traces.

  10. kainino0x commented on Nov 21, 2018

    @kainino0x
    Contributor

    Indeed, we have been planning to have a non-specced "dev-tools mode/debug mode" where, probably:

    • every operation is synchronous and immediately throws an exception if it encounters an error
    • additional validation for cross-platform consistency may be done, if it's too expensive to do otherwise
  11. kvark commented on Jul 24, 2020

    @kvark
    Contributor

    I just found the VK_EXT_robustness2 extension in Vulkan that provide equal strictness to D3D, and I believe this should be our target for WebGPU spec.

  12. austinEng commented on Jul 24, 2020

    @austinEng
    Contributor

    vulkan.gpuinfo.org says that this is present on 0% of android devices, 10.3% of Linux devices, and 5.4% of windows devices :-/

    https://vulkan.gpuinfo.org/displayextension.php?name=VK_EXT_robustness2

  13. kvark commented on Jul 24, 2020

    @kvark
    Contributor

    @austinEng it's very new (<6 month old), so these numbers will be growing. All desktop GPUs have to implement this for D3D anyway, so exposing this extension should be straightforward. On Android (and desktop GPUs on platforms where we have to use Vulkan, and the drivers are old), we'll need to have a plan B.

  14. austinEng commented on Jul 24, 2020

    @austinEng
    Contributor

    Ah, I see. This is in the issue for "Out-of-bounds behavior in shaders". Are you suggesting this behavior only for uniform/storage buffer access, or also the vertex fetch, index buffer access, etc. ?

  15. kvark commented on Jul 24, 2020

    @kvark
    Contributor

    I'm suggesting this behavior to be specified and enforced for all buffer/texture usage, including the vertex fetch and index buffers.

  16. Kangz commented on Jul 27, 2020

    @Kangz
    Contributor

    I just found the VK_EXT_robustness2 extension in Vulkan that provide equal strictness to D3D, and I believe this should be our target for WebGPU spec.

    I don't think it's practical to enforce this restriction on all accesses. On Android that doesn't have the extension (and might not have it built in the hardware) there will be a huge emulation cost (if at all possible). Robust access for vertex/index buffers being consistent would be nice, but for SSBO / UBO I think we're better off doing array clamping + minBufferBindingSize.

  17. austinEng commented on Jul 27, 2020

    @austinEng
    Contributor

    Agreed; I think that we would need to see convincing numbers that emulation is not a perf regression on mobile platforms. We haven't tested emulation on Android yet. iOS is a concern as well since vertex pulling benchmarks showed a perf regression there. It is yet to be determined if validate+discard is faster, but for now we've agreed that discard should be allowed behavior.

  18. misyltoad commented on Aug 11, 2020

    @misyltoad

    Out of bounds reading/writing should be considered undefined behaviour.

    Robustness is primarily for emulating other graphics APIs or for portability.

  19. kainino0x commented on Aug 11, 2020

    @kainino0x
    Contributor

    for portability

    Web applications written against WebGPU should be portable across hardware, and that's exactly why we require robustness.

  20. kainino0x commented on Aug 11, 2020

    @kainino0x
    Contributor

    Note that the behavior is still not fully defined - but we limit it to a finite set of undefined values like Vulkan's robustness, and that's necessary for security.

  21. Kangz commented on Sep 2, 2021

    @Kangz
    Contributor

    The group decided on out of bounds behavior for WGSL. I think we might be able to close this issue. @litherum I'll let you do it if you agree with this assessment.

  22. added
    wgsl
    on Sep 28, 2021
  23. added a commit that references this issue on Sep 6, 2022
  24. shi-yan commented on Nov 30, 2023

    @shi-yan

    Is the behavior mentioned somewhere in the spec (I wan't able to find it.)? my test on chrome/mac seems to suggest "clamping"

  25. dj2 commented on Nov 30, 2023

    @dj2
    Member

    https://www.w3.org/TR/WGSL/#ref-for-invalid-memory-reference%E2%91%A2 It's a dynamic error so the implementation can decide what it wants to do. The one you're testing on is clamping, but that isn't the only possible behaviour.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    investigationwgsl

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions