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
GPUDevice is a "reference" to an internal concept, "device".
The device is internally synchronized.
GPUDevice is "serializable" (with forStorage = false), so it can be sent via postMessage. It is not transferable.
When it's serialized, a pointer to its "device" is sent.
When it's deserialized, a GPUDevice(Ref?) with the same "device" is created.
Immutable (immutable resources or immutable objects not referencing mutable resources):
GPUSampler
GPUShaderModule
GPUComputePipeline
GPURenderPipeline
GPUPipelineLayout
GPUBindGroupLayout
(Please mention if I've misclassified any of these.)
Alternative 1
All of these objects are transferable, but not serializable.
Problem: Say you have a GPUBuffer B, and two GPUBindGroup BG1 and BG2
that contain B. How do you transfer them?
Transferring BG1 would have to also detach B.
Options when BG1 is transfered but BG2 is not:
Implicitly detach B. Loses the reference to B, so it can't be destroyed.
Make B internally held by BG1 so that B must be in the transfer list too.
Make B visibly referenced by BG1 so that B must be in the transfer list too.
All of these options implicitly destroy BG2.
Things get quite complex once you need to transfer a GPUCommandBuffer, all of the GPUBindGroups it uses, and all of the GPUBuffers and GPUTextures they use.
Alternative 2
All of these objects are serializable, but not transferable.
Problem: Now all objects can be accessed from multiple threads in parallel (including map, destroy, etc.) It becomes necessary to implicitly synchronize between threads in order to be able to use them safely. Race conditions become more likely.
Alternative 3
Mutable resources are transferable.
Containers are neither transferable nor serializable.
Immutable objects are serializable.
Problem: This allows for threaded resource initialization, and potentially for threaded submission of command buffers to queues, but it doesn't allow creating command buffers on threads and then transferring them to another thread for submit.
Conclusion
The best idea I've come up with so far is Alternative 2.
Reacted by ShuangLiu, Brandon Tsang, Raj Siva-Rajah and HALBY
Reacted by Dzmitry Malyshau, Job Talle, ShuangLiu, Alexander Drozdov, Raj Siva-Rajah and HALBY
Thanks @kainino0x for the investigation! You seem to have the spec written already as well, great :D
Mutable resources:
Can we consider them really as "(Immutable Resource, Device Reference)" pair? Methods like mapping to host, creating a texture view, or resetting a fence, are all internally using a device anyway in Vulkan and D3D12. Any "mutating" aspect would fall into the internal mutability (and share-ability) of the Device, which we have in place anyway.
With this in mind, I think all the objects should be serializable and not transferable (Alternative 2).
This analysis is missing a characterization of patterns that existing apps use. I can provide some information about common patterns in Metal (in the next few days) but I can only surmise common patterns in D3D or Vulkan.
In Metal, there are quite a few designs that authors have used. Here's a list (in rough importance order)
Asynchronous texture & buffer uploads
Asynchronous shader compilation
Asynchronous pipeline state creation
Using MTLParallelRenderEncoder
Each thread in a thread pool records into its own command buffer. This is less performant than MTLParallelRenderEncoder because you have to split your passes, thereby incurring barriers and flushes
Vulkan and D3D12 equally benefit from cases 1, 2, 3, 6, 7
For (4), secondary command buffers are used in Vulkan to record parts of a render pass separately. It's an open question if our GPUBundle objects would benefit the same scenario.
For primary command buffers, recording one per render target is a good and popular use case (e.g. used by Source 2 in slide 29). Imagine a typical deferred rendering pipeline, you could have a command buffer for the g-buffer pass, resolve + alpha pass, as well as for each light shadow map.
I can add more spec text for these later, but I need to do more work to figure out what the specification of internal slots looks like. For now I think we understand what they mean.
... If they can't be postMessaged at all today, there is cross-thread observable behavior to be backwards compatible to, and we can probably transparently upgrade these objects to shared objects ...
Checking - did you mean "there is no cross-thread behavior to be backwards compatible to"?
Checking - did you mean "there is no cross-thread behavior to be backwards compatible to"?
Oops, quite right! Corrected in the post.
That's great but is that what's needed for WebGPU? WebGPU objects are effectively just opaque ids. There's nothing else shared IIUC.
Indeed it might not be what's needed. But let's go back to the original use case and I'll try to tie it all together for why the design is inter-related.
IIUC, the original use case is that WebGPU would like a way to set up some communication channel ahead of time (i.e. like a ConcurrentQueue) that you postMessage ahead of time, and then use that from worker threads to communicate the WebGPU objects to avoid the asynchrony of postMessage.
Okay, great.
The design challenge is that if we design a ConcurrentQueue in today's world where there are no actual shared objects, the only way the ConcurrentQueue would work is something like "serialize on write, deserialize on read", and build in some magic sharing of the backing-store on serialize/deserialize like what happens for SharedArrayBuffer today across postMessage.
But this is not an attractive design for a future world we want with actual shared objects. Since there's independent desire and already momentum to get to that future with actual shared objects via Wasm (and JS) proposals, it's worth considering how we want WebGPU objects work in that future.
In that future with actual shared memory, a ConcurrentQueue would read and write actual shared objects so no serializing/deserializing is needed. I understand for WebGPU the "wrapper recreation cost" is not a real problem since there just aren't that many textures or buffers or whatever, but this is not the case for general multithreaded programs, which is why we're designing actual shared objects. The problem in that future is that shared objects cannot reference unshared objects, as that wouldn't be thread-safe. (Where the Wasm shared-everything proposal comes in that it would provide the building blocks to write such a ConcurrentQueue in userland.)
So what are the design choices here in a future with actual shared objects? I see at least two I find palatable.
Try to make WebGPU objects themselves actually shared somehow. This has the back compat thorniness I raised above.
Have WebGPU objects expose some kind of opaque token that is considered an actual shared object, as well as the ability to create new WebGPU objects backed by that opaque token. IOW, expose the magically-shared-backing-store concept to userland. This token is what can go into something like ConcurrentQueue; user code can have convenience wrappers that do the serializing/deserializing themselves. This avoids the back compat issue but requires rewrapping, but since you don't consider that problematic that seems fine.
Note that the idea of ConcurrentQueue was to work around the fact that there was no concept of shared object at the time. What we'd really like is for to have shared objects to represent WebGPU things so that they can be used concurrently with as little scaffolding as possible.
We can't make the WebGPU objects shared because we need to keep back compat. So either we do something like 2), or we add a shared: true to all object descriptors that changes the method to return a GPUObjectShared instead of GPUObject.
Note that the idea of ConcurrentQueue was to work around the fact that there was no concept of shared object at the time. What we'd really like is for to have shared objects to represent WebGPU things so that they can be used concurrently with as little scaffolding as possible.
Well you still have to communicate these WebGPU objects to other threads somehow, right? If you don't want to postMessage each one individually, you have to communicate some kind of shared container ahead of time so you can use that as the synchronous communication channel. ConcurrentQueue is just a standin for a synchronous communication channel.
Edit: To be more explicit, even in the future we're proposing with actual shared objects, there's still no implicitly available globally shared state. For a thread to get access to an actual shared object, you'll still need to communicate it to the thread first via postMessage, after which that thread can use it synchronously.
In our case I think we'd want to use shared table<shared externref> in emscripten to have per object tables, and then the WGPUObject C++ type will be an ID used to access the table. The tables would be passed to the new worker/thread in some way, like the SharedArrayBuffer used for the linear memory for example.
is it the case that these WebGPU objects can't be postMessaged at all today?
Yes. But as Gregg said, breaking non-primitive-typed expando properties on shareable objects is almost certainly a no-go.
2. Have WebGPU objects expose some kind of opaque token that is considered an actual shared object, as well as the ability to create new WebGPU objects backed by that opaque token. IOW, expose the magically-shared-backing-store concept to userland. This token is what can go into something like ConcurrentQueue; user code can have convenience wrappers that do the serializing/deserializing themselves. This avoids the back compat issue but requires rewrapping, but since you don't consider that problematic that seems fine.
This is potentially appealing. We could even probably update some function signatures to accept the token types in addition to the wrapped types, so the application doesn't always have to re-wrap. Though in that case it becomes more similar to the shared: true idea.
Can users change the [[Prototype]] of these WebGPU objects today?
I'd have thought WebIDL would disallow this, but in Chrome I can Object.setPrototypeOf(b, {}) on a GPUBuffer and it is reflected in b.__proto__. So I guess yes. But I would be surprised if anyone is currently doing this, so it's probably OK to have a breaking change here.
(caveat: I haven't looked at this thread in a long time and I don't remember everything we talked about)
I am making a PR to remove some multithreading text from the current spec.
Prior to this PR, here is the text we had in the privacy-and-security section:
WebGPU is designed to later support multi-threaded use via Web Workers. As such, it is designed not to open
the users to modern high-precision timing attacks. Some of the objects,
like {{GPUBuffer}} or {{GPUQueue}}, have shared state which can be simultaneously accessed.
This allows race conditions to occur, similar to those of accessing a `SharedArrayBuffer`
from multiple Web Workers, which makes the thread scheduling observable.
WebGPU addresses this by limiting the ability to deserialize (or share) objects only to
the [=agents=] inside the [=agent cluster=], and only if
the [cross-origin isolated](https://web.dev/coop-coep/) policies are in place.
This restriction matches the [mitigations](https://hacks.mozilla.org/2020/07/safely-reviving-shared-memory/)
against the malicious `SharedArrayBuffer` use. Similarly, the user agent may also
serialize the [=agents=] sharing any handles to prevent any concurrency entirely.
In the end, the attack surface for races on shared state in WebGPU will be
a small subset of the `SharedArrayBuffer` attacks.
I am actually not sure this is correct anymore, so I removed it entirely. I believe the multithreading scheme I was building for buffer mapping had all of the shared mutable state on the device timeline, and no shared mutable state on the content timelines. This would mean that mutating/observing shared states requires a round-trip to the device timeline. This probably does not require cross-origin isolation, so we would need to check if anything else requires it. It's something we will need to revisit when we do multithreading.
Activity
kainino0x commentedon Jul 13, 2019
I've started working on this (or rather, I've started writing spec text for device/adapter, because I felt we needed it to explain multi-worker).
kainino0x commentedon Jul 16, 2019
That work (WIP) is here: http://kai.graphics/gpuweb/spec/
Here's my investigation/thoughts so far:
Devices
GPUDevice is a "reference" to an internal concept, "device".
The device is internally synchronized.
GPUDevice is "serializable" (with forStorage = false), so it can be sent via postMessage. It is not transferable.
When it's serialized, a pointer to its "device" is sent.
When it's deserialized, a GPUDevice(Ref?) with the same "device" is created.
Error stack state is per (device, realm) pair.
Encoders
These are neither transferable nor serializable.
Other objects
Mutable resources:
Containers (objects referencing mutable resources):
Immutable (immutable resources or immutable objects not referencing mutable resources):
(Please mention if I've misclassified any of these.)
Alternative 1
All of these objects are transferable, but not serializable.
Problem: Say you have a GPUBuffer
B, and two GPUBindGroupBG1andBG2that contain
B. How do you transfer them?Transferring
BG1would have to also detachB.Options when
BG1is transfered butBG2is not:B. Loses the reference toB, so it can't be destroyed.Binternally held byBG1so thatBmust be in the transfer list too.Bvisibly referenced byBG1so thatBmust be in the transfer list too.All of these options implicitly destroy
BG2.Things get quite complex once you need to transfer a GPUCommandBuffer, all of the GPUBindGroups it uses, and all of the GPUBuffers and GPUTextures they use.
Alternative 2
All of these objects are serializable, but not transferable.
Problem: Now all objects can be accessed from multiple threads in parallel (including map, destroy, etc.) It becomes necessary to implicitly synchronize between threads in order to be able to use them safely. Race conditions become more likely.
Alternative 3
Mutable resources are transferable.
Containers are neither transferable nor serializable.
Immutable objects are serializable.
Problem: This allows for threaded resource initialization, and potentially for threaded submission of command buffers to queues, but it doesn't allow creating command buffers on threads and then transferring them to another thread for submit.
Conclusion
The best idea I've come up with so far is Alternative 2.
kainino0x commentedon Jul 16, 2019
@litherum PTAL
kvark commentedon Jul 16, 2019
Thanks @kainino0x for the investigation! You seem to have the spec written already as well, great :D
Can we consider them really as "(Immutable Resource, Device Reference)" pair? Methods like mapping to host, creating a texture view, or resetting a fence, are all internally using a device anyway in Vulkan and D3D12. Any "mutating" aspect would fall into the internal mutability (and share-ability) of the Device, which we have in place anyway.
With this in mind, I think all the objects should be serializable and not transferable (Alternative 2).
kainino0x commentedon Jul 16, 2019
Is the distinction then "(immutable resource + mutable device reference)" vs "(immutable resource + immutable device reference)"?
litherum commentedon Jul 16, 2019
This analysis is missing a characterization of patterns that existing apps use. I can provide some information about common patterns in Metal (in the next few days) but I can only surmise common patterns in D3D or Vulkan.
litherum commentedon Jul 31, 2019
In Metal, there are quite a few designs that authors have used. Here's a list (in rough importance order)
MTLParallelRenderEncoderI hear that (5) is popular on Direct3D 12, too.
kvark commentedon Jul 31, 2019
Thanks for the list, @litherum !
Vulkan and D3D12 equally benefit from cases 1, 2, 3, 6, 7
For (4), secondary command buffers are used in Vulkan to record parts of a render pass separately. It's an open question if our
GPUBundleobjects would benefit the same scenario.For primary command buffers, recording one per render target is a good and popular use case (e.g. used by Source 2 in slide 29). Imagine a typical deferred rendering pipeline, you could have a command buffer for the g-buffer pass, resolve + alpha pass, as well as for each light shadow map.
grorg commentedon Aug 5, 2019
Discussed at 5 August 2019 Teleconference
kainino0x commentedon Aug 8, 2019
#399 #400 #401 #402
I can add more spec text for these later, but I need to do more work to figure out what the specification of internal slots looks like. For now I think we understand what they mean.
kainino0x commentedon Oct 1, 2020
More explanation on multi-threading to help facilitate discussion:
https://github.com/gpuweb/gpuweb/wiki/The-Multi-Explainer#multi-threading-javascript
kainino0x commentedon Jun 28, 2021
Tentative explainer section on multithreading: https://gpuweb.github.io/gpuweb/explainer/#multithreading
31 remaining items
kenrussell commentedon Feb 22, 2024
@syg :
Checking - did you mean "there is no cross-thread behavior to be backwards compatible to"?
syg commentedon Feb 22, 2024
Oops, quite right! Corrected in the post.
Indeed it might not be what's needed. But let's go back to the original use case and I'll try to tie it all together for why the design is inter-related.
IIUC, the original use case is that WebGPU would like a way to set up some communication channel ahead of time (i.e. like a ConcurrentQueue) that you
postMessageahead of time, and then use that from worker threads to communicate the WebGPU objects to avoid the asynchrony ofpostMessage.Okay, great.
The design challenge is that if we design a ConcurrentQueue in today's world where there are no actual shared objects, the only way the ConcurrentQueue would work is something like "serialize on write, deserialize on read", and build in some magic sharing of the backing-store on serialize/deserialize like what happens for
SharedArrayBuffertoday acrosspostMessage.But this is not an attractive design for a future world we want with actual shared objects. Since there's independent desire and already momentum to get to that future with actual shared objects via Wasm (and JS) proposals, it's worth considering how we want WebGPU objects work in that future.
In that future with actual shared memory, a ConcurrentQueue would read and write actual shared objects so no serializing/deserializing is needed. I understand for WebGPU the "wrapper recreation cost" is not a real problem since there just aren't that many textures or buffers or whatever, but this is not the case for general multithreaded programs, which is why we're designing actual shared objects. The problem in that future is that shared objects cannot reference unshared objects, as that wouldn't be thread-safe. (Where the Wasm shared-everything proposal comes in that it would provide the building blocks to write such a ConcurrentQueue in userland.)
So what are the design choices here in a future with actual shared objects? I see at least two I find palatable.
Try to make WebGPU objects themselves actually shared somehow. This has the back compat thorniness I raised above.
Have WebGPU objects expose some kind of opaque token that is considered an actual shared object, as well as the ability to create new WebGPU objects backed by that opaque token. IOW, expose the magically-shared-backing-store concept to userland. This token is what can go into something like ConcurrentQueue; user code can have convenience wrappers that do the serializing/deserializing themselves. This avoids the back compat issue but requires rewrapping, but since you don't consider that problematic that seems fine.
Kangz commentedon Feb 23, 2024
Note that the idea of
ConcurrentQueuewas to work around the fact that there was no concept of shared object at the time. What we'd really like is for to have shared objects to represent WebGPU things so that they can be used concurrently with as little scaffolding as possible.We can't make the WebGPU objects shared because we need to keep back compat. So either we do something like 2), or we add a
shared: trueto all object descriptors that changes the method to return a GPUObjectShared instead of GPUObject.syg commentedon Feb 23, 2024
Well you still have to communicate these WebGPU objects to other threads somehow, right? If you don't want to
postMessageeach one individually, you have to communicate some kind of shared container ahead of time so you can use that as the synchronous communication channel.ConcurrentQueueis just a standin for a synchronous communication channel.Edit: To be more explicit, even in the future we're proposing with actual shared objects, there's still no implicitly available globally shared state. For a thread to get access to an actual shared object, you'll still need to communicate it to the thread first via
postMessage, after which that thread can use it synchronously.Kangz commentedon Feb 23, 2024
In our case I think we'd want to use
shared table<shared externref>in emscripten to have per object tables, and then theWGPUObjectC++ type will be an ID used to access the table. The tables would be passed to the new worker/thread in some way, like theSharedArrayBufferused for the linear memory for example.kainino0x commentedon Feb 27, 2024
Yes. But as Gregg said, breaking non-primitive-typed expando properties on shareable objects is almost certainly a no-go.
This is potentially appealing. We could even probably update some function signatures to accept the token types in addition to the wrapped types, so the application doesn't always have to re-wrap. Though in that case it becomes more similar to the
shared: trueidea.I'd have thought WebIDL would disallow this, but in Chrome I can
Object.setPrototypeOf(b, {})on a GPUBuffer and it is reflected inb.__proto__. So I guess yes. But I would be surprised if anyone is currently doing this, so it's probably OK to have a breaking change here.kainino0x commentedon Jul 25, 2024
(caveat: I haven't looked at this thread in a long time and I don't remember everything we talked about)
I am making a PR to remove some multithreading text from the current spec.
Prior to this PR, here is the text we had in the privacy-and-security section:
I am actually not sure this is correct anymore, so I removed it entirely. I believe the multithreading scheme I was building for buffer mapping had all of the shared mutable state on the device timeline, and no shared mutable state on the content timelines. This would mean that mutating/observing shared states requires a round-trip to the device timeline. This probably does not require cross-origin isolation, so we would need to check if anything else requires it. It's something we will need to revisit when we do multithreading.