Repository navigation
Description
Context
This is a continuation of a discussion that was had on the WebGPU matrix. There has been some discussion of this problem in #2229 but was not the primary topic.
As of the writing of this issue, the WGSL spec defines all atomics as operating on dedicated Atomic types. This is consistent with how MSL does atomics, but differs from how GLSL/SPIRV/HLSL/DXIL do atomics. They do "untyped" atomics where you can do an atomic operation on any T.
The purpose of this issue is to evaluate the issues with the current way WGSL does atomics and determine if WGSL could have "untyped" atomics.
The Problem with Atomic<T>: Machine Translation from Other Languages
A very common path for the use of WebGPU and by extension WGSL, is through porting a project onto the web platform. These projects are written in some other source language and are being transpiled to WGSL. As it stands, such a machine translation might not be possible without conservatively promoting too much to atomics.
Take the following GLSL:
layout(set = 0, binding = 0) buffer PrimeIndices {
uint[] indices;
};
How should that be translated to WGSL if a static index 15 is accessed?
It could promote the entire array to atomics array<atomic<u32>> which would pessimise other reads.
It could pull some heroics and split the array into 3 parts, a array<u32, 15> header, a atomic<u32> middle and a array<u32> footer. This would over-promote anything that accessed 15 non-atomically, but leave the rest of the array unscathed. This messes with the minimum binding size and is definitely something I consider "crazy" to expect implementations to do.
How should that be translated to WGSL if a dynamic index is accessed?
The translator would have no choice but to over-promote to array<atomic<u32>>.
Can We Do Untyped Atomics
On all backends with the exception of MSL, we can do untyped atomics just fine. On metal, in order to do an atomic operation you need to have that explicit type.
Casting
When presented with an atomic, spirv-cross translates this to an explicit cast from the non-atomic type to the atomic type.
See https://shader-playground.timjones.io/6ac47edae3a6940746a1b92e06dc7836 for the full source, but the important bit is that it translates:
atomicExchange(indices[0], 2)to
atomic_exchange_explicit((device atomic_uint*)&_10.indices[0], 2u, memory_order_relaxed);
This kind of re-interpretation seems a bit sketchy at first but is not without president within Apple's own example code. In their example code Modern Rendering with Metal they don't cast, but they reinterpret that same threadgroup variable as both a atomic_uint* (Renderer/Shaders/AAPLLightCulling.metal:551) and a float* (Renderer/Shaders/AAPLLightCulling.metal:531).
Mixing Atomics and Non-Atomics
The question becomes, if we determine that untyped atomics are a thing we want, how should we describe the behavior if the user mixes and matches atomics and non-atomics?
I don't have a solid formal answer to this, but logically this feels no different from racing non-atomic reads and non-atomic writes across a RW buffer without barriers. In the case of racing non-atomics, you end up with some unspecified value, possibly an old value, possibly reading a partial write. We don't want to ban that for obvious reasons, so this would be no worse than the situation there.
Trying to get around this by statically defining what is an atomic (through Atomic or validation) is just as overly restrictive as trying to solve the problem of the racing non-atomics and has similarly unspecified results.
Conclusion
I have tried to express a route that we could make untyped atomics work in WGSL. I think this is particularly important as it falls into the category of "preserving developer trust". For years before they could run on metal and use untyped atomics through spirv-cross, but us coming in and deciding that you can't do that, is the kind of thing that would really put people off of WebGPU.
If there are any questions or if anything needs clarification, please ask. I can also edit the post to include other pointers pro/con.
Activity
alan-baker commentedon Dec 2, 2021
@litherum for comments on casting in Metal.
alan-baker commentedon Dec 2, 2021
For reference, this was discussed in #1360 (comment) as part of the original proposal.
litherum commentedon Dec 3, 2021
Yeah, that comment you linked to is correct. Casting in the general case would be no bueno, and mixing atomics and non-atomics would be the same. This isn't a situation like depth textures; we really need this type for atomics to work at all.
dneto0 commentedon Dec 3, 2021
I sympathize with people seeing this as a loss of functionality, coming from other platforms to WebGPU. It is a loss.
Using casting tricks may trick the tools into letting you do what you want, today, on shipped implementations. But that's not the programming model promised by the stack. The MSL constraints are inherited from C++14, and what you're asking for is non-starter in C++14.
There was a somewhat similar situation where I very much wanted the ability to form a pointer to a component in a vector. After close reading of C++14, I found this was not allowed because it violates the type-based alias analysis rules.
See the discussion here: #1931 (comment)
In that case, an MSL vector type does not count as an "aggregate" or "union", which meant you couldn't write the memory as one type (e.g. vector) and read it as another (e.g. vector component). Similarly, a C++ atomic type does not count as an aggregate or union over its contained integer type. So the whole implementation stack (compiler and machine) is not built to do what you're asking.
About "preserving developer trust". That only counts or has meaning when you've already restricted yourself to features that are available in WebGPU itself. In this case, what you're asking is outside what WebGPU can do.
Now, it would be great if you could convince Apple to add the feature to a supported shader language. Then I'd be first in line to enable it in WGSL and WebGPU.
m-schuetz commentedon Dec 3, 2021
This is unfortunate because at least for point cloud rendering in OpenGL, mixing non-atomic reads with atomic writes can be an enormous performance boost (up to 4x). The non-atomic reads allow us to do an early-depth test, and thereby avoid a large amount of superfluous atomic writes. Unfortunately I wasn't able to check if atomic loads are a suitable replacement in our case since I couldn't get atomicLoad to work in OpenGL.
I'm mostly afraid that atomic loads would force global memory access. However, the GLSL atomicLoad extension seems to support specifying the scope within which the call is atomic. Is this something that could be done in WebGPU?
[1] https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_memory_scope_semantics.txt
dneto0 commentedon Dec 3, 2021
The GL_KHR_memory_scope_semantics extension exposes the Vulkan memory model to GLSL. It's not supported on OpenGL, which is explains why atomicLoad doesn't work in OpenGL.
Yes, atomic loads will force an access that goes all the way out to the authoritative copy of the memory, i.e. past all the caches.
See https://gpuweb.github.io/gpuweb/wgsl/#scoped-operations, which explains how the WGSL atomics map to Vulkan memory model concepts.
In particular:
Also, WGSL atomics are always relaxed.
If buf.x is in a storage buffer, then WGSL's
is the same as the GLSL:
If buf.x is in workgroup, then the GLSL would be:
alan-baker commentedon Dec 3, 2021
MSL and HLSL don't support specifying atomics with fine-grained scoping like you're asking for. In order to implement the same behaviour everywhere, the scope needs to be based on storage class. So while we could spec an atomicLoad that had a workgroup memory scope for storage buffers, it would still be implemented by a device atomic in HLSL and MSL.
litherum commentedon Dec 3, 2021
I think I was a bit too curt in #2377 (comment). The reason is that it’s undefined behavior to read/write using atomic operations and then read/write using non-atomics. The type system is a way to enforce that this never happens, and this must be enforced for the security guarantees of WGSL.
Kangz commentedon Dec 6, 2021
Note that this would be undefined behavior in other shading languages too. However undefined behavior there isn't "anything goes" but that the exact values you read / write to memory aren't completely defined (but they can't be leftover data from someone else).
Can you explain why this is important to uphold the security guarantees of WGSL? The WebGPU synchronization scopes should mean that the only undefined values you load / write are the page's own value, not someone else's values. So while undefined, it is safe undefined behavior no?
m-schuetz commentedon Dec 6, 2021
If Metal seems capable of casting/reinterpreting the array from atomic to non-atomic in one of their examples, would it be feasible to do the reverse in WebGPU? Reinterpreting an atomic memory location as a non-atomic memory?
kvark commentedon Dec 6, 2021
@dneto0
Could you explain this bit? We are talking about fragment shaders here, there are no synchronization barriers within a render pass. So what forces the driver to go all the way to the "authoritative copy"? No sync means any value from the cache should be fine (i.e. correct according to guarantees we can provide), as long as the cache was populated in this render pass.
m-schuetz commentedon Dec 6, 2021
Does that also hold for compute shaders? Because that's where I'd like to mix atomic/non-atomic access (or atomicLoad from cache).
kvark commentedon Dec 6, 2021
Unless you have a
storageBarrier/workgroupBarrierbetween a store and a load, I don't see why the driver would need to force its way into the global/workgroup memory, respectively.This is a bit speculative. I'm asking @dneto0 to help with building this kind of intuition.
m-schuetz commentedon Dec 6, 2021
QueueFamily seems to be a pretty broad scope already? Compared to workgroup scope.
33 remaining items
litherum commentedon Feb 2, 2022
Thanks, that's helpful.
I edited the code to add
layout(local_size_x = 2) in;. Sorry about omitting it.The fact that HLSL and GLSL disagree about this is concerning.
Just so I'm on the same page, can you demonstrate a correct (and nontrivial) program that does this in GLSL?
raphlinus commentedon Feb 2, 2022
Also, it's not called "memory model" in the D3D specs, it's called "memory consistency model." That search would bring you to Section 7.14 of the D3D11.3 Functional Spec. Another highly relevant part of that is the documentation of the sync instruction. These are for D3D11, but as far as I know there are no significant changes to the memory model in D3D12.
The language is very informal and operational, especially compared with something like the Vulkan memory model which has Alloy code, or the C+11 memory mode which has had over a decade of practical use and academic work. That said, I don't think it's meaningless. The relevant quote here is "The D3D11 Shader Memory Consistency Model is weak/relaxed, as generally understood in existing architectures and literature." One reasonable interpretation is that results are generally consistent with the PTX memory consistency model, with some exceptions. The most interesting section is 7.14.2 which states that a race between a nonatomic write and an atomic operation in threadgroup shared memory produces "undefined results". The section goes on to state that atomics in UAV (device) memory are atomic with respect to both nonatomic loads and stores, which I think actually does answer your proposed HLSL litmus test above: this is guaranteed to terminate with 5 in the buffer.
I could be wrong in my interpretation, and am very interested in collecting examples where some implementation behaves differently than what I stated.
Just saw this as I was writing:
Because you said nontrivial, I'm comfortable posting the coarse path rasterizer from piet-gpu. That probably looks scary because it's very dense in 2D computational geometry (it's doing highly optimized flattening, conservative rasterization, and coarse winding number calculation), but the memory access patterns are reasonably straightforward. There's an
atomicExchangeon line 251 which builds a linked list, and writes into the same buffer (through an abstraction) on line 279; these basically resolve tomemory[offset] = data;. (there's also an atomic add on line 225, but it's not super relevant to this discussion)What's going on here is that there is a data structure (specifically an array of
Tile, which is an element ofPath) which is dynamically allocated in theuint memory[]array by an earlier pipeline stage. This data structure has one field which is always updated with atomic exchange. Other accesses to this memory pool are regular nonatomic reads and writes. All this is fairly conservative with respect to memory model; within a dispatch, any given memory address has either all atomic accesses or all nonatomic accesses.A similar pattern is the bounding box calculation in the path segment processor, and this might actually be a clearer example. Basically, there's logic to determine whether the path segments contributing are contained entirely within one partition (workgroup), and if so the aggregated bounding box is written directly using nonatomics. But if the path segments straddle a partition boundary, the partial aggregate is accumulated using atomic min/max operations. This shows that the choice of whether to use atomics or no is dynamic and dependent on the input data. It would be possible to always use atomics, but it would potentially be a performance hit (I expect the nonatomic case to be a significant majority of writes).
dneto0 commentedon Feb 17, 2022
I'm glad you're pushing on this.
In GLSL, you need to use GL_KHR_memory_scope_semantics in order to have a precise memory model kick in. That's what enables the use of the Vulkan memory model.
Without that, GLSL is in the same boat as HLSL: it does not have a satisfactory memory model that can answer the detailed questions you're asking. Also Metal leans heavily on C++14, but that's incomplete in certain respects. (For example, just like OpenCL 2.0, Metal doesn't say anything useful about concurrent accesses to image memory, particularly when it might alias with memory mapped as "device".) At a coarse grain, none of HLSL, MSL, or plain GLSL actually tell us enough to go on, by spec, because they don't have the necessary rigor in their descriptions/manuals/documentation.
Back to your example from this comment.
Let's copy that example, but add the use of the Vulkan memory model:
This program is racy in the Vulkan memory model. There are many executions where the atomic and non-atomic will race.
To make it non-racy, you have to ensure there is "enough" synchronization between the store in one invocation and the read-modify-write in the other. Here "enough" stands for a bunch of verbiage covered by "location-ordered" in the memory model.
A few patterns will work. The simplest is to put a control+memory barrier between the non-atomic store and the atomic read-modify-write. If we assume there is only one workgroup then a regular barrier will work:
If there can be more than one workgroup, then we need more. That's because a regular GLSL control barrier only orders invocations within the same workgroup.
So we now need a handoff combining barriers and atomics to make sure events are ordered across workgroups.
See the synchronizes-with section. I think the most straightforward one is
This is what it looks like. Because the focus is on inter-workgroup communication, I simplified things and made each workgroup only have one invocation.
*** EDIT. I was so focused on preventing the races between the two phases of nonatomic and atomic writes that I forgot about the nonatomic writes between invocations. So this version of the program still allows races between invocations purely on the nonatomic writes. That wasn't the focus of the question, I don't think, so I'll leave it as is, with this note.
dneto0 commentedon Feb 17, 2022
Right. In Vulkan memory model terms, @raphlinus is taking advantage of a memory barrier at the API level, to create a "system-synchronizes-with" relation between the non-atomic accesses in one dispatch and the atomic accesses in a subsequent dispatch (and vice versa).
The accesses are thus location-ordered by the case that starts with
The memory barrier at API level between the different dispatches is the "domain operation" here.
And I'm sure all that is jargon that makes no sense until you spend a whole bunch of time grokking the Vulkan spec.
dneto0 commentedon Feb 17, 2022
Amusingly, the pattern in @raphlinus' application has correct well-specified behaviour in OpenCL 2.0 pdf
In particular, 3.3.6.4 Memory Ordering Rules: Host-side and Device-side Commands has the relevant clauses:
and the work of kernels enqueued on in-ordered command queues respect the queue order:
m-schuetz commentedon Feb 17, 2022
Software-rasterization of point clouds with atomicMin. A cheap non-atomic early-depth test determines if an expensive atomicMin operation is required.
raphlinus commentedon Feb 17, 2022
I believe this is not quite correct. That GLSL extension unlocks a whole slew of built-in functions and flags, but does not by itself change the SPIR-V. In order to do that, you also add
#pragma use_vulkan_memory_model, which sets the VulkanMemoryModel capability, changes OpMemoryModel to Vulkan, and makes quite a range of other changes to generated SPIR-V. Key among those is adding MakePointerAvailable/Visible and NonPrivatePointer to nonatomic loads and stores to buffers withcoherentGLSL qualifications. My understanding is that you have to set these capabilities in the SPIR-V, and also request vulkanMemoryModel in the PhysicalDeviceVulkanMemoryModelFeatures passed in at device creation. Otherwise the spec guarantees nothing.There's a whole other discussion to be had about what semantics to expect from GLSL/SPIR-V/Vulkan when the memory model is not fully opted into. I'm not sure how valuable it is to get into that, but happy to add my 2¢ if people are interested.
dneto0 commentedon Feb 17, 2022
I took a look this morning. The only change adding
#pragma use_vulkan_memory_modeldoes is change the memory scope on the barrier and the compare-exchange from "Device" to "QueueFamily", and add the associated capabilityOpCapability VulkanMemoryModelDeviceScope. The material difference occurs when a single device has been partitioned into multiple sets of "queue families". That's kind of beside the point in this discussion.There is no difference with respect to non-private or the makepointeravailable/visible: in my sample program the availability an visibility operations are done in bulk by the barriers.
For completeness I'm attaching the disassembly of the two versions.
handoff_with_pragma.spvasm.txt
handoff.spvasm.txt
Definitely yes, you have to explicitly detect and opt into the Vulkan memory model at the Vulkan API level.
dneto0 commentedon Feb 17, 2022
Two things:
raphlinus commentedon Feb 17, 2022
I think I have an answer to the mystery of why David's program does not require explicit
#pragma use_vulkan_memory_modelbut why my prefix.comp example does. David's program specifiesgl_SemanticsVolatilewhich maps to Volatile memory sematics. That particular value requires VulkanMemoryModel capability, while the stuff used in my prefix sum implementation (explicit device scope, acquire/release) does not. Lesson: you have to be careful if you explicitly want Vulkan memory model semantics, otherwise you're basically depending on a compiler heuristic.Whether volatile is appropriate is another question. My feeling is that it's not, and I think there is no live proposal to map anything in WGSL to volatile semantics (though it's been brought up). If there were, I would argue against it. I think for the purpose of coordinating between workgroups (and even between host and workgroup, should the need arise), the concept of "coherent" covers what we need.
I will also confess I had a physical reaction to the execution and progress issues, but held back from commenting on them :)
amarpMSFT commentedon Feb 17, 2022
Rafael pointed me here, I'm from DX. I don't have time to follow the whole thread, but the observation about DX's weak memory model are correct. In the example of a write followed by atomic write to same address, if multiple threads in a group are fighting, a barrier is needed in between. That said, even without a barrier, if all threads always finish with the atomic, the last thread that runs will do its atomic last, so that contrived example might get away without a barrier, but I haven't thought too hard about that.
The example that tries to expect coordination across work groups is hairy (dnteo0 acknowledged that above I see). DX doesn't require "fair" scheduling, so it is possible for spinning to starve others. There are plenty of ways to get lucky. UE5 "gets away" with treading into uncharted waters here (they know it's on the edge), and it's hard to quantify exactly why.
dneto0 commentedon Feb 18, 2022
Yeah, this bug is getting super long.
To be clear:
This issue is still "Post-V1", which is appropriate. My answers in the last few days are trying to explain how mixed atomic/non-atomic accesses are supposed to work.
kvark commentedon Feb 18, 2022
My understanding of the status was that we are waiting for Apple's internal discussions to resolve, and this should happen before V1, including the potential change in the API here, depending on the outcome.
litherum commentedon Mar 1, 2022
I don't think we're going to be able to report before V1.
magcius commentedon Jun 7, 2023
Since it came up today, the Direct3D specification says that doing non-atomic loads of values written to by atomics without the storage being marked as
globallycoherentis undefined: