Skip to content

Create a proposal for multi-workerΒ #354

Open

Description

@kainino0x

In the meeting, Myles and I agreed to collaborate on a proposal for how WebGPU should work across multiple workers. Here's a tracking bug.

Activity

  1. kainino0x commented on Jul 13, 2019

    @kainino0x
    ContributorAuthor

    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).

  2. kainino0x commented on Jul 16, 2019

    @kainino0x
    ContributorAuthor

    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

    • GPUCommandEncoder
    • GPUComputePassEncoder
    • GPURenderPassEncoder

    These are neither transferable nor serializable.

    Other objects

    Mutable resources:

    • GPUBuffer
    • GPUTexture
    • GPUFence

    Containers (objects referencing mutable resources):

    • GPUTextureView
    • GPUBindGroup
    • GPUCommandBuffer
    • GPURenderBundle

    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.

  3. kainino0x commented on Jul 16, 2019

    @kainino0x
    ContributorAuthor
  4. kvark commented on Jul 16, 2019

    @kvark
    Contributor

    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).

  5. kainino0x commented on Jul 16, 2019

    @kainino0x
    ContributorAuthor

    Is the distinction then "(immutable resource + mutable device reference)" vs "(immutable resource + immutable device reference)"?

  6. litherum commented on Jul 16, 2019

    @litherum
    Contributor

    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.

  7. litherum commented on Jul 31, 2019

    @litherum
    Contributor

    In Metal, there are quite a few designs that authors have used. Here's a list (in rough importance order)

    1. Asynchronous texture & buffer uploads
    2. Asynchronous shader compilation
    3. Asynchronous pipeline state creation
    4. Using MTLParallelRenderEncoder
    5. 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
    6. Using multiple queues on the same device
    7. Using multiple devices on the same machine

    I hear that (5) is popular on Direct3D 12, too.

  8. kvark commented on Jul 31, 2019

    @kvark
    Contributor

    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 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.

  9. grorg commented on Aug 5, 2019

    @grorg
    Contributor
  10. kainino0x commented on Aug 8, 2019

    @kainino0x
    ContributorAuthor

    #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.

  11. kainino0x commented on Oct 1, 2020

    @kainino0x
    ContributorAuthor

    More explanation on multi-threading to help facilitate discussion:
    https://github.com/gpuweb/gpuweb/wiki/The-Multi-Explainer#multi-threading-javascript

  12. kainino0x commented on Jun 28, 2021

    @kainino0x
    ContributorAuthor

    Tentative explainer section on multithreading: https://gpuweb.github.io/gpuweb/explainer/#multithreading

  13. 31 remaining items

  14. kenrussell commented on Feb 22, 2024

    @kenrussell
    Member

    @syg :

    ... 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"?

  15. syg commented on Feb 22, 2024

    @syg

    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.

    1. Try to make WebGPU objects themselves actually shared somehow. This has the back compat thorniness I raised above.

    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.

  16. Kangz commented on Feb 23, 2024

    @Kangz
    Contributor

    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.

  17. syg commented on Feb 23, 2024

    @syg

    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.

  18. Kangz commented on Feb 23, 2024

    @Kangz
    Contributor

    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.

  19. kainino0x commented on Feb 27, 2024

    @kainino0x
    ContributorAuthor

    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.

  20. modified the milestones: , Milestone 2 on Jul 2, 2024
  21. kainino0x commented on Jul 25, 2024

    @kainino0x
    ContributorAuthor

    (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.

  22. added
    api-milestone-2-202502
    on Feb 19, 2025
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

    apiapi-milestone-2-202502investigationlarge

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions