Skip to content

Should the API enforce that writable storage buffer bindings don't alias each other? #1842

Description

@Kangz

This is similar to #287: should multiple storage buffer bindings used by the same entrypoint be allowed to alias? CC @alan-baker @kvark

  • Making the behavior defined in native APIs can require a special "alias decoration", and it could be very subtle to add something similar to WGSL.
  • Undefined data races from aliasing could be a portability concern.
  • Validating lack of aliasing would incur additional draw/dispatch time validation.
  • What about a storage buffer used in a draw being modified by a different draw in the same render pass (that's currently allowed).
  • Aliasing seems like it could be useful to developers to use with different types, or to give flexibility of how bindings are mapped to actual buffers (two bindings in a shader could be backed by a buffer at different offsets).

Activity

  1. added
    wgsl
    on Jun 15, 2021
  2. kdashg commented on Jun 22, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-06-22
    • DN: I thought there was no aliasing, so I’m surprised it’s back! One Q is “how much work is the API willing to do to forbid/validate this”
    • GR
    • DM: I wanted to talk about this here instead of in API group, because it’s a more important question for us to answer, and we are the ones who know what our constraints are.
    • AB: Anything is possible, but we would have to mark things as [aliased], which we would only want to avoid/do conservatively. (otherwise it’s UB)
    • MM: Code-gen can definitely be better if we avoid aliasing. Scope is not the whole renderpass though, it’s just the invocation.
    • DM: Even without aliasing, if you read and then write to a UAV, what even are our guarantees?
    • MM: If you’re not using atomics, and reading from UAV, that’s a race. The compiler doesn’t have to consider what other threads to, if not using atomics.
    • DM: So the only thing we care about aliasing is within a single shader, like does it see the same resource in two different places.
    • AB:
    • MM: If you bind the same resource to different types of bindings, they couldn’t be coherent, and you’ll get very different results on different machines.
    • AB: In a shader, different views of the same binding are ok if marked as [aliased]
    • DM: Since we don’t synchronize in this usage scope, can’t we just keep everything non-aliased?
    • (much discussion of UB)

    #1844 is the issue for bounding UB / ub.

  3. litherum commented on Jun 22, 2021

    @litherum
    Contributor

    The example I was trying to give in the call today was this:

    void foo(int* x, int* y) {
        sideEffect(*y);
        *x = 7;
        sideEffect(*y);
    }

    Ideally, we'd only have to load from y once, but if the pointers can alias, we have to load twice.

  4. Kangz commented on Jun 23, 2021

    @Kangz
    ContributorAuthor

    From my reading of the minutes it seems we worry about the UB when we have two bindings that are aliased, but it seems it might not be all classes of UB, but just undefined ordering (you can only read a value that is written by another part of your program, but you can't read out of bounds, or sprout carrots on the GPU).

    There is the same issue with writing and reading to a storage buffer without barriers, just that we don't provide anything that allows fixing the undefined ordering on aliased bindings.

  5. kvark commented on Jun 23, 2021

    @kvark
    Contributor

    @Kangz precisely, yes. My hope is that we don't have to do anything, and instead just tell the compiler that we don't expect the aliasing of bindings. The ordering behavior is still within the expectations we set up for operations within a synchronziation scope, i.e. no ordering.

    However, we really need to confirm that this is "undefined ordering" as opposed to any scarier case of UB.

    The alternative is a fairly costy validation at draw call time. We'd have to collect the writable storage bindings across all bind groups references by the layout of the current pipeline, track the binding ranges of the buffers, check for intersections, but also separate between vertex/fragment stages. We'd have to repeat that work whenever the user, say, rebinds a bind group with a different dynamic offset (which can be per draw call). It's possible that this code will be sufficiently fast, but it's still non-trivial piece that we'd have to run in the hottest (draw call) loop and tune up indefinitely.

  6. kdashg commented on Jun 29, 2021

    @kdashg
    Contributor

    I believe the general consensus is that it would be "non-trivial validation at draw call time", rather than "fairly costly validation at draw call time".

  7. kdashg commented on Jun 29, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-06-29
    • MM: I think we said that we would try the extra validation, and see how bad the perf overhead is.
    • JG: So do we need to spec something?
    • MM: Probably in the API spec
    • DN: WGSL requires no aliasing (variables reference distinct storage)
    • DM: But only within the shader, I think, not necessarily resources.
    • MM: It would be fine if they alias so long as it’s not observable
    • (consensus: back over to API)
  8. litherum commented on Jul 13, 2021

    @litherum
    Contributor

    On yesterday's call, I was describing the difference between these two things (please forgive my pseudocode):

    var myStorageBuffer : ...
    
    [threadsPerWorkgroup: (2, 1, 1)]
    func foo(threadID) {
        myStorageBuffer[0] = (threadID == 0 ? 14 : 25);
    }
    ...
    dispatch(numWorkgroups: (1, 1, 1));
    

    and

    var myStorageBuffer : ...
    
    func bar(int* a, int* b) {
        doSomething(*a);
        *b = 17;
        myStorageBuffer[0] = *a;
    }
    
    [threadsPerWorkgroup: (1, 1, 1)]
    func baz() {
        int x = 21;
        bar(&x, &x);
    }
    ...
    dispatch(numWorkgroups: (1, 1, 1));
    

    In the first case, if you inspect the value of myStorageBuffer[0] after the shader has finished running, you might read a value of 100 - that is, a value that doesn't appear anywhere within the program. In the second case, you'll either read 21 or 17, depending on whether the compiler emitted the second load or not.

  9. litherum commented on Jul 14, 2021

    @litherum
    Contributor

    Oh, hey look at that. In section 5.2 of the Metal Shading Language spec:

    Buffers (device and constant) specified as argument values to a graphics or kernel function cannot alias; that is, a buffer passed as an argument value cannot overlap another buffer passed to a separate argument of the same graphics or kernel function.

  10. kvark commented on Jul 14, 2021

    @kvark
    Contributor

    @litherum wait, this is much worse than our original issue. It means, even read-only access to buffers can't alias... so more stuff to track down for each binding + pipeline configuration.
    Also, does this mean that Metal is fine with aliased textures (including writable textures)?

  11. litherum commented on Jul 14, 2021

    @litherum
    Contributor

    It turns out the documentation isn't quite precise enough.

    1. Access to aliased resources is okay, as long as data inside the aliased region is only read, and both resources have the same type (which means same access qualifiers and everything).
    2. The rule applies to all resources, not just buffers.
    3. This rule does not apply to resources in argument buffers. It's just about arguments to entry points.

    I've filed rdar://80551882 and rdar://80551807 to update the documentation.

  12. Kangz commented on Jul 19, 2021

    @Kangz
    ContributorAuthor

    So in all cases if an implementation chooses to use argument buffers, then it is allowed to alias stuff? Seems like Metal doesn't give a constraint for the aliasing discussion.

    In the first case, if you inspect the value of myStorageBuffer[0] after the shader has finished running, you might read a value of 100 - that is, a value that doesn't appear anywhere within the program.

    That seems unlikely given how hardware usually work. Metal/MSL don't provide any guarantee themselves but it seems safe that the underlying hardware has some granularity for memory accesses and that some serialization happens in the memory controller. (at worst each bit can have only a value, 0 or 1, that was written to it, but not one that was not written. But things most likely happen at byte level or more).

  13. kainino0x commented on Jul 19, 2021

    @kainino0x
    Contributor

    Resolution:
    For now, add something to the spec that says "[writable] bindings must not alias", but don't add an actual validation error. Add an "Issue(#1842):" that says to revisit this and figure out if we should add a validation error. Meanwhile, implementations are responsible for deciding what to do:

    • Pretend it's fine and issue the aliased draw to Metal anyway
    • Print a warning and lose the device
    • etc.
  14. benvanik commented on Jul 20, 2021

    @benvanik

    Happy to see this won't be validated - pooling/suballocation + bind group caching + non-trivial storage buffer access would make it nearly impossible to use WebGPU for complex compute cases if the API was trying to validate this based on what the bindings describe about buffers.

  15. added a commit that references this issue on Aug 24, 2021
  16. 12 remaining items

  17. added a commit that references this issue on Nov 7, 2022
  18. added a commit that references this issue on Nov 7, 2022
  19. dneto0 commented on Nov 7, 2022

    @dneto0
    Contributor

    With #3581, the WGSL side has been relaxed to allow the overlaps of storage among resource variables.
    Because the case is now allowed, we had to refine what a "memory view" was, so that it meshes correctly with the memory model.

  20. kdashg commented on Jan 11, 2023

    @kdashg
    Contributor
    GPU Web 2023-01-04/05 APAC-timed
    • KN: discussed this in multiple meetings. Minuted resolution - say it's invalid to do this, but not validate it. Somewhat-undefined behavior if you alias writable storage buffers. Concerns about writing "undefined behavior" in the spec. And, having this be undefined at all. Should discuss again.
    • MM: new context - now, in the shading language, there's a resolution to have static analysis ensuring pointers don't alias. This particular issue is the API analogue to that issue which has a resolution.
    • KG: if people are comfortable, think it's fine.
    • KN: what was the WGSL change? Allowing variables to alias? Suggestion is that the API also allows variables to alias?
    • KG: think so.
    • JB: there's an analysis in WGSL preventing variables from aliasing, right now. That's a different kind of aliasing - aliasing of pointer arguments.
    • KN: OK. Thing David linked to is something different. https://github.com/gpuweb/gpuweb/pull/3581/files
    • MM: unstated - pointers in shading language & pointers to buffers in bindgroups should be considered the same. They're just pointers.
    • JB: since we took steps about this in the shading language you're saying to do the same thing at the API level?
    • MM: yes.
    • JB: it's zero overhead at runtime in the shading language. Here, the validation would be per-draw-call, expensive. Not sure how that was resolved.
    • MM: resolution there was - we did not agree whether the cost was worth the benefit. Spec'll say it's illegal, but not validated.
    • MM: imagine a shader, 2 RW buffers. At runtime, they alias. End up writing to one, assuming the other didn't get modified.
    • KN: WGSL spec says - it's a dynamic error if you have 2 resource variables that are mutable with overlapping memory.
    • MM: what's the analysis Jim and I are remembering?
    • JB: it applies to pointer arguments to user-defined functions. Sounds to me - WGSL already addressed this question. Decision was - pointer args can't alias. Global variables to buffers - if they alias, you're on your own.
    • MM: don't remember that.
    • KN: this WGSL change was in November.
    • JB: a dynamic error permits impls to detect it, if they like.
    • KG: more like user error.
    • MM: boils down to - can a dynamic error make us invalidate the command buffer?
    • KN: don't think so. Would have to write that on the API side.
    • JB: dynamic errors can't invalidate the command buffer. They show up once we're running the code.
    • KN: yes, but could cause the draw call to not happen.
    • MM: could cause previous draws to not happen. When you encode the command, detected as programmer error, could invalidate command buffer.
    • KN: why do you want that?
    • MM: for earlier example. Because compiler doesn't know things alias, RWs don't seem coherent.
    • KN: consequence?
    • MM: wrong results. Could lead to more dynamic errors.
    • KN: WebGPU's not free of wrong results.
    • MM: not sure I agree with that - possible to write a (...) program in WebGPU.
    • KG: idea is that if it runs on your machine, it's likely to run on others.
    • KN: lots of things in the spec where we can't guarantee how they work.
    • MM: I'm assuming pushback is because of performance. If we could quantify the perf cost, that would help me change my mind.
    • KG: not just perf cost, also functionality. Imagine 2 structured bindings, on one, only access evens - on the other, odds. Hardware supports it. If you do this interleaved aliasing - technically safe. But, our naive rules couldn't differentiate from a "real" aliasing that breaks. Forbidding aliasing also forbids benign aliasing.
    • MM: in comparison - what happened with uniformity analysis?
    • JB: lot of discussion.
    • KG: there are multiple opt-outs. Finished them in Dec 13 meeting minutes.
    • MM: maybe some way for author to say, I know my bindings alias.
    • KR: the major concern about putting this in at all is the perf cost. Per-draw-call validation is a major bottleneck in WebGL and we don't want to introduce these in WebGPU.
    • KN: the english-language algorithm: https://gpuweb.github.io/gpuweb/#abstract-opdef-encoder-bind-groups-alias-a-writable-resource
    • JB: indirect draw calls? How would the analysis work? Thorny. Couldn't do that until you have the contents of the buffers in hand.
    • KG: depends on what level we're doing this. If you alias sections of the buffer - we can determine that.
    • KN: can set pipeline and bind groups, then draw as much as you want. Most times, not a lot of draw calls per bind group.
    • JB: what about dynamic offsets? Are they OK too?
    • KN: that'd also invalidate the validation.
    • JB: sounds really thorny to me.
  21. Kangz commented on Jan 13, 2023

    @Kangz
    ContributorAuthor

    Following up on the last meeting where we thought maybe the decision that WGSL storage buffers are "coherent": talking to @alan-baker he confirmed that his is only useful for accesses of the same buffer through the same bind point. (my understanding is that it makes writes to that buffer visible to future reads through the same bind point).

    However if two bind point A and B point to the same buffer, the Vulkan Memory Model doesn't give any guarantees that the writes to one become immediately visible to the other. In fact two references to the same memory location through different bind point are considered to be different references. One reason for this for example is that the compiler could want to be smart and reorder the memory accesses:

    var<storage> a : array<f32, 2>;
    var<storage> b : array<f32, 2>;
    
    // This code could be transformed to reduce the number of memory writes
    b[0] = value0;
    var read1 = a[0]; // Contains value0
    b[1] = value1;
    
    // into
    var read1 = a[0]; // Contains the value at the start of the shader.
    b = array<f32, 2>(value0, value1);

    So we can't rely on coherent to make this work magically for us. In fact I don't think we can ensure that this work in fragment shaders, and in compute shaders we'd have to put storage barriers everywhere.

    However, I'm still of the opinion that validating at the API side that bound storage buffer ranges don't overlap will be a developer pain that's more costly than the cases where it prevents aliasing from being a footgun:

    • Developers that want to interleave data in storage buffers, for example because it is some kind of bump allocator will be tripped when they try to merge allocators together while keeping the same shader that has different bind points. (For example @raph does Vello happen to have any cases like this?)
    • The cases where developers write to the same buffer from two places not on purpose seem like they would be rare.
    • Developers doing advanced compute are much more likely to get tripped by regular data races, the lack of barriers to make storage writes visible to all workgroups, the granularity of data races when writing to elements of vectors, etc. Of course less footguns is better, but this seems like an advanced case that mostly experts would use.
    • Developers will want to use the "default size" of storage buffer bindings such that they only have to define the offsets. This includes the whole rest of the buffer in the range, so developers risk getting confused when they see their two bindings produce a validation error.

    Given the tradeoff between usefulness for expert / developer surprise on one side, and additional validation / one less niche footgun on the other side, I'd rather no validate this. But I understand some would weight the tradeoffs differently.

  22. litherum commented on Jan 18, 2023

    @litherum
    Contributor

    Tentative resolution: Validation at draw call time (at least until someone tells us that the perf cost is unacceptable)

    If an implementation wants to validate as much as possible at bind group creation time (to ease the draw call perf cost), it can, it just can't report the error immediately; it should just save a bit in the bind group, to be reported later

    This applies to both storage buffers and storage textures.

  23. added
    copyediting
    on Jan 18, 2023
  24. kainino0x commented on Jan 18, 2023

    @kainino0x
    Contributor

    Moving to editorial to update the spec.

  25. austinEng commented on Jan 24, 2023

    @austinEng
    Contributor

    Clarification question:

    Does this validation apply across all bindings in bind groups in the currently-bound pipeline layout at draw/dispatch time. OR does it only apply to bindings that are actually statically used in the shader at draw/dispatch time?

  26. kainino0x commented on Jan 28, 2023

    @kainino0x
    Contributor

    The proposed optimization for precomputing a structure at bind group creation time requires that we look at the whole bind group (which according to the API rules can't have more or fewer entries than its layout). So with that optimization, allowing aliasing in bindings not used by the shader would take extra time on top, to fixup false negatives.

    Generally speaking I don't think we introspect into the shader except at pipeline creation time. So the pipeline layout (bind group layouts) is all we actually care about for validation. This is how the currently written algorithm works:
    https://gpuweb.github.io/gpuweb/#abstract-opdef-encoder-bind-groups-alias-a-writable-resource

    So that's my proposal. Added it to next week's agenda though.

  27. shrekshao commented on Jan 31, 2023

    @shrekshao
    Contributor

    Does the buffer binding aliasing take into account the dynamic offsets of the bind group? Looks like a yes at #1842 (comment)

    If so maybe we need to update the spec language at section https://gpuweb.github.io/gpuweb/#buffer-binding-aliasing

  28. Kangz commented on Feb 1, 2023

    @Kangz
    ContributorAuthor

    Does the buffer binding aliasing take into account the dynamic offsets of the bind group? Looks like a yes at #1842 (comment)

    Yes it definitely should and the spec should be updated if it doesn't.

  29. kainino0x commented on Feb 28, 2023

    @kainino0x
    Contributor

    For the record here's what discussion we have of the optimization technique:
    https://github.com/gpuweb/gpuweb/wiki/Minutes-2023-01-18#should-the-api-enforce-that-writable-storage-buffer-bindings-dont-alias-each-other-1842
    (found by searching "1842" in the meeting minutes folder)

    CW: if people complain about runtime cost we can reconsider.
    KG: if you want to avoid costs, you can inline all bindgroups together. Checked at BindGroup creation time.
    MM: you're talking about app, not the implementation?
    KG: yes.
    CW: so you're saying validate at BG creation and draw call?
    MM: no, you're already doing that. Create BG; 2 obviously-conflicting resources. You can clearly detect that at BG creation time.
    CW: spec doesn't mandate it.
    KG: no, but we'd do it.
    MM: that's the core of why I think the validation won't be that bad.
    KG: so we're checking all the bind groups against each other. Lighter-weight than WebGL.
    KN: slightly reduces amonut of draw time validation but not that much. Instead of NxN you have Nx(number of things in bind group). Still quadratic.
    MM: can sort, then do binary search rather than linear scan.
    KG: don't have to put everything in same bind group. All buffer bindings in same bind group, they're pre-checked.
    KN: can prebuild sets, check for set membership.
    KG: also, in WebGL, hard to do anything faster than checking buffer object and its length. Don't need to do that pointer chasing anymore. Everything inline in bindgroup. Should be cheap.
    KN: hopefully.
    CW: for V1, in Chrome, we might do the quadratic thing and figure it out later.
    KG: we do something similar for index validation in WebGL and never did anything better because it works.
    CW: OK.** Resolution: will take this validation, taking into account buffer ranges.** Only draw call time, not bind group creation. There's implementation choice. I asked Raph Levien but no answer yet.
    MM: so if you create a bind group with two things obviously colliding, we won't fail BG creation but will fail later draw calls with it?
    CW: yes. Can currently add 2 TextureViews in same BG that conflict for example.
    MM: if you have 2 seemingly conflicting things, e.g. one in vertex shader and one in fragment shader, those don't collide.
    CW: correct.

  30. self-assigned this
    on Mar 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

copyediting

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions