Skip to content

Atomics proposal #1360

Closed
Closed

Description

@alan-baker

Atomic Type

Add a new type, atomic<T>, to WGSL. For MVP, T must be either u32 or i32. Atomics may only be placed in variables in the workgroup or storage storage classes. Atomics may only be operated on by atomic builtin functions.

Translation

In both HLSL and SPIR-V, atomic<T> should be translated the same as T. In MSL, atomic<T> should translate as volatile atomic_uint or volatile atomic_int.

Atomic Functions

Add the following builtin functions:

  • atomicAdd(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicMax(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicMin(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicAnd(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicOr(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicXor(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T
  • atomicExchange(atomic_ptr : ptr<SC, atomic<T>>, value : T) -> T

In all the above cases, the return value is the original value in the atomic prior to the operation.

Also add compare exchange:

  • atomicCompareExchangeWeak(atomic_ptr : ptr<SC, atomic<T>>, expected : T, value : T) -> vec2<T>

Compare exchange returns a vec2 where the first element is the original value in the atomic and the second value is whether or not the comparison was successful (1 for success, 0 otherwise). This uses the weak version of compare exchange which means that the comparison can fail spuriously (i.e. even if expected matches the original value).

The memory ordering for all atomic functions is relaxed (see section 29.3 of the C++14 specification). This means that no synchronization or ordering guarantees are made on non-atomic memory accesses, nor on atomic memory accesses operating on different memory addresses (i.e. unless they are mutually ordered atomics).

For all atomic functions, the storage class of atomic_ptr must be workgroup or storage. Atomics on storage storage class are device atomics (e.g. Device memory scope in SPIR-V), while atomics in workgroup storage class are workgroup atomics (e.g. shared variable atomics in HLSL).

Atomic functions must not be used in vertex shaders.

Example:

[[block]] struct A {
  atomic<u32> a;
  array<u32> rta;
};

var<storage> myVar : A;

// ...

const old : u32 = atomicAdd(myVar.a, 1);

Translation

WGSL SPIR-V HLSL MSL GLES
atomicAdd OpAtomicIAdd InterlockedAdd atomic_fetch_add_explicit atomicAdd
atomicMax OpAtomic[S|U]Max1 InterlockedMax atomic_fetch_max_explicit atomicMax
atomicMin OpAtomic[S|U]Min1 InterlockedMin atomic_fetch_min_explicit atomicMin
atomicAnd OpAtomicAnd InterlockedAnd atomic_fetch_and_explicit atomicAnd
atomicOr OpAtomicOr InterlockedOr atomic_fetch_or_explicit atomicOr
atomicXor OpAtomicXor InterlockedXor atomic_fetch_xor_explicit atomicXor
atomicExchange OpAtomicExchange InterlockedExchange atomic_exchange_explicit atomicExchange
atomicCompareExchangeWeak OpAtomicCompareExchange2 InterlockedCompareExchange3 atomic_compare_exchange_weak_explicit atomicCompSwap
  1. Signedness is based on T.
  2. SPIR-V only provides the strong compare exchange.
  3. If used in a loop, the loop must be annotated with the attribute [allow_uav_condition]

Considerations

The new type favours translations from WGSL to other dialects (as opposed to translation to WGSL). MSL requires C++ style atomic types. If just i32 or u32 were used, then the declaration of the variable would need to be modified by its usage, which should generally be avoided. One implication of this choice is that not all HLSL or SPIR-V programs will be convertible to WGSL as those languages support atomic operations on regular memory addresses (no special types). One example is if the SPIR-V or HLSL atomic operates on 32-bit integer in a vector. Translating to WGSL (from SPIR-V and HLSL) has the problem avoided in avoid translating from WGSL to MSL (the use must modify the declaration).

Survey of Implementations

Metal (MSL)

Provides atomic_int and atomic_uint types, so 32-bit integer atomics only. Atomic functions only support memory_order_relaxed (no synchronization with other memory operations). Atomic functions are defined in <metal_atomic>. These functions are not limited by the shader stage.

Metal 1.0 supports the following functions for volatile threadgroup (workgroup) and device atomic memory objects:

  • Atomic_store_explicit
  • Atomic_load_explicit
  • Atomic_exchange_explicit
  • Atomic_compare_exchange_weak_explicit
  • Atomic_fetch_key_explicit
    • And, or, add, max, min, sub, xor

Signedness based on memory type
Signed versions use two’s complement with silent wrap around (i.e. same as SPIR-V)
Metal 2.0 added support for non-volatile versions of the atomic functions.

The biggest difference from SPIR-V is that atomic types are required. Atomic operations cannot be performed on any memory object. MSL also does not support atomic image operations (i.e. no atomics through OpImageTexelPointer).

DirectX (HLSL)

HLSL supports interlocked (atomic) functions on int and uint data types since Shader Model 5. HLSL also supports atomic exchanges on any scalar data type. There are no restrictions on shader stage for any of the functions. Atomics can be performed on shared (workgroup) or resource (storage and texture) variables. All atomic operations use relaxed memory ordering.

The following functions are supported:

  • InterlockedAdd
  • InterlockedAnd
  • InterlockedCompareExchange
    • When used in a loop, the loop must be annotated with [allow_uav_condition] (in compute shaders)
    • Unclear if this is a strong or weak compare exchange
  • InterlockedCompareStore
    • Could be mapped to compare exchange
  • InterlockedExchange
  • InterlockedMax
  • InterlockedMin
  • InterlockedOr
  • InterlockedXor

Vulkan (SPIR-V)

Vulkan supports 32-bit integer atomics in Vulkan 1.0. There are extensions to support 64-bit integer atomics and float/half/double atomics (load, store, exchange, min, max, add). Vulkan also supports integer atomic operations on texel components (via OpImageTexelPointer). The memory scope for atomics must be Workgroup or Device (QueueFamily). The storage class of pointers must be: Workgroup, StorageBuffer (and PhysicalStorageBuffer), Uniform (BufferBlock) or Image. Vulkan supports atomics in compute shaders unconditionally, but requires feature bits (fragmentStoresAndAtomics and vertexStoresAndAtomics) to work in Fragment and Vertex shaders. WebGPU currently forbids vertexStoresAndAtomics.

Vulkan supports the following operations:

  • OpAtomicLoad
  • OpAtomicStore
  • OpAtomicExchange
  • OpAtomicCompareExchange
    • Strong version
  • OpAtomicIIncrement
  • OpAtomicIDecrement
  • OpAtomic[I|F]Add
  • OpAtomicISub
  • OpAtomic[U|S|F]Min
  • OpAtomic[U|S|F]Max
  • OpAtomicAnd
  • OpAtomicOr
  • OpAtomicXor

Weak Compare Exchange

The weak version of atomic compare exchange may fail spuriously. That is, the comparison may fail even if the expected value matches the value in the atomic memory location. The weak version should generally be used when the cost of failure is low and be put into a loop until it succeeds. The cost of the strong version is much higher than the weak version on some systems and should be used for single tests.

Activity

  1. added
    wgsl
    on Jan 21, 2021
  2. added this to the MVP milestone on Jan 21, 2021
  3. dneto0 commented on Jan 21, 2021

    @dneto0
    Contributor

    In #978 I argued that WGSL should have volatile atomics. I presume the proposed builtins would all be the volatile versions.

  4. alan-baker commented on Jan 21, 2021

    @alan-baker
    ContributorAuthor

    In #978 I argued that WGSL should have volatile atomics. I presume the proposed builtins would all be the volatile versions.

    It should likely depend on whether WGSL adopts volatile as a modifier or not.

  5. dneto0 commented on Jan 21, 2021

    @dneto0
    Contributor

    I mean that WGSL should specify their behavior as if they are volatile, whether or not the keyword exists: each apparent access specified in the program source should be executed, i.e. you can't optimize them away assuming some constraints on the scheduling of other threads. (or something like that. See the issue).

  6. alan-baker commented on Jan 21, 2021

    @alan-baker
    ContributorAuthor

    I understand, I was saying if there is a volatile modifier then you don't have to say that atomics are inherently volatile, but if that modifier isn't added I agree it's best to just say they are volatile.

  7. dneto0 commented on Jan 22, 2021

    @dneto0
    Contributor

    It's too bad atomic-load and atomic-store are not supported.

    How about emulating them on HLSL with atomic-or with a 0 value?

  8. dneto0 commented on Jan 22, 2021

    @dneto0
    Contributor

    Or rather:

    • implement atomic-load with InterlockedOr with a 0 value
    • implement atomic-store as InterlockedExchange, but discard the old value after you got it.
  9. litherum commented on Feb 16, 2021

    @litherum
    Contributor

    We had a discussion with the Metal team about whether atomic types are really necessary to expose in the language, or whether we could have WGSL work like HLSL and just make the implementation of the atomic functions in MSL internally reinterpret_cast their parameters to their corresponding atomic types. However, the Metal team says this would be no good very bad, and an atomic type really needs to be part of WGSL (the reinterpret_cast trick would not work in general).

  10. litherum commented on Feb 16, 2021

    @litherum
    Contributor

    Presumably atomic operations shouldn’t need to be inside uniform control flow.

  11. litherum commented on Feb 16, 2021

    @litherum
    Contributor

    A few thoughts:

    1. The function signatures say things like “ptr<SC, atomic> atomic_ptr”. Shouldn’t that be “atomic_ptr : ptr<SC, atomic>”
    2. The example has
      atomic a;
      …
      atomicAdd(myVar.a, 1);
      I think we’re still in discussions about how pointers will work, so that pointers discussion needs to be concluded before these signatures are finalized.
    3. What will the implementation strategy be for WGSL -> HLSL compilers re: “[allow_uav_condition]”? Spray it everywhere? Do program-wide analysis to determine where it needs to go? Specialize? Why does HLSL require the author to provide this annotation instead of HLSL compilers internally detecting where it needs to go?
  12. litherum commented on Feb 16, 2021

    @litherum
    Contributor

    @alan-baker this is a wonderfully researched and presented proposal! Thank you so much!!!

  13. alan-baker commented on Feb 16, 2021

    @alan-baker
    ContributorAuthor
    1. The function signatures say things like “ptr<SC, atomic> atomic_ptr”. Shouldn’t that be “atomic_ptr : ptr<SC, atomic>”

    Thanks, I've fixed the signatures.

    1. The example has
      atomic a;
      …
      atomicAdd(myVar.a, 1);
      I think we’re still in discussions about how pointers will work, so that pointers discussion needs to be concluded before these signatures are finalized.

    I agree. The most important thing in my opinion is facilitating the syntax in the example for programmer ease-of-use. So whether the signature retains the ptr or just uses atomic directly can be resolved with the pointer discussion.

    1. What will the implementation strategy be for WGSL -> HLSL compilers re: “[allow_uav_condition]”? Spray it everywhere? Do program-wide analysis to determine where it needs to go? Specialize? Why does HLSL require the author to provide this annotation instead of HLSL compilers internally detecting where it needs to go?

    The allow_uav_condition attribute is also only necessary in compute shaders according to the HLSL documentation. Unfortunately, I don't see an alternative to program analysis unless we want to expose a similar attribute in WGSL.

  14. pow2clk commented on Feb 16, 2021

    @pow2clk

    The [allow_uav_condition] requirement is somewhat contorted by the documentation linked above. for loop docs give a more nuanced picture.

    At any rate, this is a relic of FXC that is not relevant to DXC. Additionally, the only way of generating HLSL from WGSL that I'm aware of will make use of SPIRV-Cross, which doesn't seem to support this. So if this is a requirement, it will be a requirement for spirv-cross.

  15. litherum commented on Feb 16, 2021

    @litherum
    Contributor

    the only way of generating HLSL from WGSL that I'm aware of will make use of SPIRV-Cross

    I believe both Google and Mozilla have publicly stated at the beginning of the last F2F that their long term plans include compiling directly from WGSL to HLSL/MSL without going through SPIR-V. (Please correct me if I am mistaken.)

  16. dj2 commented on Feb 16, 2021

    @dj2
    Member

    Tint has backends for both MSL and HLSL now, they are not enabled in Chromium yet, but will be used for Origin Trials.

  17. pow2clk commented on Feb 17, 2021

    @pow2clk

    I've completed an invigorating code archeology expedition which has revealed that at least since 2016 (and possibly much sooner), FXC has also ignored the allow_uav_condition attribute. The documentation for InterlockedCompareExchange is clearly inaccurate and also out of date. We'll address that.

    Regardless of how the HLSL is generated, if the FXC version used to compile it to DXBC is at least more recent then 2016, the attribute can be left out entirely. If earlier versions of FXC need to be used, then we can look closer at exactly when this change was made.

  18. added a commit that references this issue on Feb 18, 2021
    99aa341
  19. kdashg commented on Mar 5, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-02-16
    • (initial socialization)
    • AB: quick overview, after looking at other languages, came up with this proposal. Comment from MM that this may want to wait on pointers. Important part is the usage example, other than that, adding a new type to facilitate translation to metal which is more restrictive than HLSL or SPIR-V.
    • MM: Appreciate that the type was added, and was bracing for an argument. Interested in the allow_uav_condition. Can some describe where it’s needed and what it does in HLSL?
    • GR: Not sure.
    • MM: Don’t think it’s urgent, but could delay. GR can you take an AI?
    • GR: Who added it?
    • MM: It’s an HLSL language annotation?
    • GR: No it isn’t, it’s to account for something in HLSL but don’t know what it is.
    • AB: Listed in note in compareExchange. So brought it over in the survey but don’t know what it’s for
    • JG: Looks like an HLSL thing.
      DN: Listed in the for statement as a qualifier on something. Loop shader termination condition to be based off of …. (see link)
    • https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-while
    • GR: Not familiar with, will look into it.
    • MM: Would be valuable to know more. Notwithstanding, I think the proposal is great and should land ASAP.
    • JG: Prioritization vs other stuff?
    • MM: Think the cost benefit trade offs are in proposals favour. All 3 APIs roughly agree, so impl isn’t super hard, seen in a lot of shaders. Think they should be in v1.
    • DN: Brandon was converting examples and barriers and atomics cropped up pretty quickly in compute shaders. Atomics for compaction rounds. A fundamental building block.
    • MM: You’re on a parallel processor, atomics are useful.
    • DM: Is that in tint yet?
    • DN: No we wait for spec first.
    • DM: Looked at the proposal, seems reasonable, maybe more feedback once implemented.
    • JG: Portability, repeatability problems? Question is just the reality we’re stuck with here, I’m only bringing up for completeness. Will cause bugs that don’t reproduce.
    • MM: Agree but the cost/benefit tradeoff is for this. This makes it easier to write non-portable algorithms, but allows writing algorithms you couldn't write anyway.
    • JG: Maybe we need tsan for WebGPU.
    • DN: None of the APIs are good about details like forward progress and this lets you play and discover. Agree with MM’s comments.
    • JG: Sounds good.
    • DM: Do these need to accept a pointer to an atomic?
    • AB: Still open for discussion. Written this way because to me it was important to spec no copying was being done, has to be a ref of some kind. Want to clarify ptr or ref is fine, but not in spec yet.
    • MM: Propose we get started with anything for the function signatures. Get it ready, put in spec, run with it and when we figure out ptr/ref we come back and adjust. Don’t think the exercise of adjusting the proposal will be super hard.
    • DM: So, you want this to be a type, but the type would make no sense if it’s used in a struct that is local to the shader? It only makes sense for storage buffers/
      AB: Workgroup and storage.
    • MM: Correct. In metal you can’t take an atomic op and pretend it’s an int. You can’t add 5 to it. Only thing you can do is the set of atomic functions.
    • DM: If only used in those blocks or structs, don't we need to make an attribute of the field instead of part of the type?
    • MM: Depends on how ptrs end up working
    • DM: I mean how we declare them, could it be an [[atomic]] decoration for a field.
    • AB: Goes with if the pointer is passed to a function do you carry the decl?
    • MM: If i have a helper that takes a ref to an atoci how do we represent
    • RM: Need to make clear what’s an atomic and that the loads and stores don’t look like normal loads and stores
    • MM: +1
    • DM: If it’s a type, can I declare a struct with these types in them?
      MM: In metal you can, you can call functions on them
    • JG: On the struct?
    • MM: No, on the field.
    • AB: One minor point is the question of volatility. Good to say they translate to volatile for now, and add a keyword later. Would add that now that they do, metal requires that now
    • JG: Says we’d have to translate it on metal, but not elsewhere. So, implementation detail. Are you suggesting we allow users to set volatile.
    • AB: Yes, either need to make it volatile or let users set it
    • MM: Vote we don’t add volatile
    • JG: Could be part of our atomics stuff
    • AB: That’s fine too.
    • JG: Needs specification.
    • MM: Will we do the thing DN suggested about atomic_load and store and polyfilling on SPIR-V
    • AB: HLSL you need to fill them all
    • JG: Idea has a big +1. Seems like a win to just give folks the polyfill unless there is extra cost. If you want to do an atomic load on HLSL this is how you do it, and we can just do it in the builtin.
    • MM: Think it’s valuable for complex math ops that can’t be expressed as an atomic. You want to do a load and store and make them distinct but as a type you can’t just pretend it’s an int and do the math. So, I think it’s valuable.
  20. added a commit that references this issue on Mar 10, 2021
    96cb70c
  21. dneto0 commented on Mar 13, 2021

    @dneto0
    Contributor

    My summary of the issues from the 02-16 meeting:

    • consensus it's a good feature for v1
    • only the builtins can operate on the atomic variables (memory locations).
    • specify the atomic operations are volatile (have volatile behaviour; not defining a general 'volatile' feature)
    • function prototypes, particularly how to pass the atomic variable into them, is pending resolution of the pointer/ref discussion.
    • desire to polyfill atomic load and atomic store. (I still want to think carefully that that is valid. It converts a read to a read-modify-write. But since it's on an atomic location it should be ok because the total order is maintained?)
  22. dneto0 commented on Mar 31, 2021

    @dneto0
    Contributor

    In prep for next week's meeting, "atomics in a pointer world", I think this is the relevant example:

    Let's assume we have #1569.

    Example in this context:

    [[block]] struct B { a: i32; };
    [[group(0),binding(0)]] var<storage> buf: B;
    [[stage(compute)]] foo() {  
       let newValue = atomicAdd.........;
    }

    Should we have:

          atomicAdd(atomic_ptr : ptr<SC, atomic<T>>, v : T) -> T
    

    Usage: let newValue = atomicAdd(&(buf.a), 1);

    or this, if we also allow function parameters with ref type, at least for built-in functions.

          atomicAdd(atomic_ref : ref<SC, atomic<T>>, v : T) -> T
    

    Usage let newValue = atomicAdd(buf.a, 1);

  23. kvark commented on Apr 1, 2021

    @kvark
    Contributor

    When you have ref in the type system, it's tempting to start exposing it out like this...

    But there is no need here, really. @litherum pointed out that MSL atomics work on a pointer argument, so we should just follow, instead of trying to invent new grounds here.

  24. kdashg commented on Apr 7, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-04-06
    • MM: Probably should be using pointers. 1. Consistency with existing languages (like MSL). 2. Consistency within WGSL. 3. Same logic as desire for explicit ampersand.
    • AB: If we do pointers, we don’t need to change.
    • MM: Should we talk about loads and stores?
    • AB: I wrote up how we could emulate them. I think we discussed whether to do this in the past and agreed.
  25. dneto0 commented on Apr 7, 2021

    @dneto0
    Contributor

    The resolution was that the atomic built-ins act on a pointer-to-the-atomic.

  26. added a commit that references this issue on Apr 8, 2021
    839972c
  27. added a commit that references this issue on Apr 8, 2021
    5f46921
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

    wgsl

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions