Skip to content

Proposal: queued data transfers #491

Closed

Description

@kvark

This is an evolution of #154 initiated by the discussion in #418 (comment) .
It can be seen as an alternative to #481. Also related to #488.

Problem

Data transfers are hard. Different platforms have different physical memory properties as well as different restrictions in the APIs in how they can be used. For example, there are unified (UMA) and non-unified memory architectures, and there "hybrid" platforms that are non-unified in general but expose a small chunk of unified memory. In the API space, D3D12 has a notion of "upload" and "download" heaps that are only supposed to be used for staging data going in and out of the fast local VRAM.

The native API expose memory access to CPU via mapping. On the Web, the situation is different:

  • the client code and data may be separated from the GPU by a process boundary
  • operations can't block
  • concurrent access to the data hurts application portability

The different needs ask us to consider different solutions for the API. In particular, it is appealing to provide an API that hides the UMA/non-UMA differences while still using the most efficient code path on those platforms.

Solution

One of the important building blocks for a performant streaming/transfer system is a "staging belt" (name is invented, don't search for it). It's a ring buffer of CPU-visible persistently mapped buffers that are used to temporarily host data (the "staging") while it's on the way to GPU. The structure is FIFO, and allocation is linear (the "belt"), which makes the implementation fairly straightforward. This was originally done in Dawn for data uploads via GPUBuffer::setSubData method.

In order to control the lifetime of the staging blocks, we need to associate the upload operations with a GPUQueue. This is the main difference from #154. The API could look like this:

partial interface GPUQueue {
  // Start uploading data. The pass has to be finished before anything can be
  // done to the queue, such as submits or other upload passes.
  GPUUploadPass beginUpload();
}

dictionary GPUTextureDataLayout {
  u32 rowPitch;
  u32 imageHeight;
};

dictionary GPUUserData {
  ArrayBuffer data;
  unsigned long offset;
};

interface GPUUploadPass {
  // Stops recording the upload operations.
  // Detaches all the temporary `ArrayBuffer` objects.
  void finish();

  // Upload the CPU data into the specified destination buffer.
  // If `data` is provided, the contents are used for the upload, and `nil` is returned.
  // If `data` is not provided, a new `ArrayBuffer` object is returned. In this case,
  // the `ArrayBuffer` gets detached at the point where `finish` is called.
  ArrayBuffer uploadBuffer(
    GPUBuffer destination,
    GPUBufferSize destinationOffset,
    GPUBufferSize size,
    GPUUserData? userData);

  // Upload the CPU data into the specified destination texture.
  ArrayBuffer uploadTexture(
    GPUTextureDataLayout layout,
    GPUTextureCopyView destination,
    GPUExtent3D size,
    GPUUserData? userData);

  // This may also need a staging buffer.  
  void copyImageBitmapToTexture(
    GPUImageBitmapCopyView source,
    GPUTextureCopyView destination,
    GPUExtent3D copySize);
}

Explanation

The implementation would manage the "staging belt" internally, with GPUUploadPass as an interface to it.

The transfer operations are queued on the queue at the GPUUploadPass::finish() time from the user perspective. It's easy to reason about "when" things happen: after all the previous queue operations (e.g. submit() calls) and before all the subsequent operations. When an upload operation is recorded, the implementation can decide to execute it instantly, since it knows about the order of operations.

Fast path

The fast path of data transfers is writing directly into the buffer that is persistently mapped by the browser. If the platform supports mapping across the process boundary (or has no IPC), the client can also have a view into the "staging belt", possibly without any means to allocate new buffers in the ring buffer.

Upon calling uploadXxx method, the client finds the "staging space":

  • if the client sees the mapped staging belt, and it has enough space (or can be extended by the client), this mapped area is the staging
  • otherwise, the shared memory between the client and the GPU process is used as a staging.

If userData is provided, the contents are copied into the selected staging space.
Otherwise, a new ArrayBuffer object is created as the view into the staging space and returned to the user.

After the staging space is filled, we can internally queue a copy operation from this staging memory into the target resource.

In the case where the target resource is CPU-visible and is not used by the GPU, the implementation can write directly into it, which gives us the zero-copy fast path.

setSubData()

Having the GPUUploadPass in the API, it would be easy for the users to have the most efficient path for setSubData (of #418):

GPUQueue.setBufferSubData = function(buffer, offset, data) {
  let pass = this.beginUpload();
  pass.uploadBuffer(buffer, offset, data.byteLength, { data: data } );
  pass.finish();
};

FAQ

Q: Why do we need a new pass interface?
A: No strong reason. I just thought it's useful to separate the semantics of submission from transfers at the API level.

Q: Why are we only talking about uploads?
A: Just to reduce the scope, for now, given that downloads are not as important to get fast.

Q: How exactly are ArrayBuffer objects get detached?
A: (missing answer)

Finally, this isn't a polished or finalized proposal. It's quite hand-wavy, inviting us to explore this distinct API direction.

Activity

  1. magcius commented on Nov 7, 2019

    @magcius

    This looks like a direct descendant of Apple's proposal in #45.

    In terms of "detached objects", the closest equivalent I can think of is HTML5's Transferable objects, originally designed to transfer ownership between script hosts, like between workers. ArrayBuffer is already considered a Transferable object, and it's supported in browsers, so that could be something to build on top of; the object is transferred to the WebGPU runtime.

  2. kainino0x commented on Nov 8, 2019

    @kainino0x
    Contributor

    So far I really like this idea. I think it's a big improvement on the past proposals for upload passes.

    Does beginUpload need to be async so that the gpu has a chance to finish using some things?

    • On UMA, in some cases, we could theoretically wait on a fence then return a pointer directly to the buffer itself.
    • I think it would reduce the frequency with which we fallback to allocating new ipc shared memory.

    Re: detached objects: We use exactly the transferable objects semantics to detach ArrayBuffers today in unmap(), and we should continue to use that for this proposal. As for when to do it, I think finish() is the right time as proposed.

  3. magcius commented on Nov 8, 2019

    @magcius

    The only thing that concerns me is that you can't create multiple upload passes at the same time, meaning that multi-thread is limited. Actually validating this would probably be more expensive than not, but having ability to create multiple upload passes at the same time from different threads would be nice. That's the big limitation here that I see.

  4. kainino0x commented on Nov 8, 2019

    @kainino0x
    Contributor

    I was thinking multi-queue would be the right solution to that problem. Do you think it would work?

  5. kvark commented on Nov 8, 2019

    @kvark
    ContributorAuthor

    @magcius holy cow, was this issue just sitting at the back of my brain as a time bomb? I came to (indeed!) almost the same API via an entirely different trajectory :)

    @grorg sorry about completely missing your discovery in #45. I believe I was still trying to think of how explicit pipeline barriers would be exposed at this point, and the suggested transfer API felt a bit too high for me to feel comfortable. Now, having a better understanding of how complex transfers are, I think it was a good suggestion.

    Edit: I don't think "All transfers require at least one copy." drawback is correct here. I described the way an implementation could operate without copies, under certain conditions.

  6. austinEng commented on Nov 8, 2019

    @austinEng
    Contributor

    So far I really like this idea. I think it's a big improvement on the past proposals for upload passes.

    I like this idea as well!

    Does beginUpload need to be async so that the gpu has a chance to finish using some things?

    • On UMA, in some cases, we could theoretically wait on a fence then return a pointer directly to the buffer itself.
    • I think it would reduce the frequency with which we fallback to allocating new ipc shared memory.

    I don't think it would be beginUpload, but maybe uploadBufferAsync with no GPUUserData provided. We should definitely still have the synchronous version which falls back to shared memory if there's no persistently mapped memory available in the "staging belt". Maybe.. even have a timeout associated with the Async version? That way applications can make sure they don't wait too long for a Promise.

  7. Kangz commented on Nov 11, 2019

    @Kangz
    Contributor

    Agreed with everyone that it is a promising path. I really like the overloads for zero or one-copy paths and the texture uploading could make it much easier to get started with the API (slight complexity increase but helps paper over the rowpitch 256 constraint maybe?). The difference with @grorg's proposal is that it treats only uploads and is not buffered which makes it much more palatable.

    There's a lot to like here but I don't think it is a local maximum yet, so I'll focus on the negative points, but again, it does look like a great start.

    Issues with the current proposal for GPUUploadPass

    Encourages small staging areas.

    The shape of the API providing small ArrayBuffers (for the zero-copy path) returns one object for each upload. This means that if you want to update N small regions in a dynamically updated vertex or uniform buffer, the application will have to get N small ArrayBuffers. This is less efficient than batched copies that are possible with a smart "staging manager" in an application that uses GPUBuffer.mapWriteAsync where staging memory is updated all at once, and then small copies are pipelined with copyBufferToBuffer

    An extra pass adds validation pitfalls

    This was already raised by @magcius for multithreaded environment but also for an application the upload pass adds a validation state that if not managed correctly will cause validation errors and misrendering. Contrast this with GPUQueue.Submit and GPUQueue.writeToBuffer (if we have it) that is atomic w.r.t. the validation state tracking.

    Also it makes it less clear when ArrayBuffers are neutered, if it is on finish or GPUQueue.submit there is less a correlation between the methods and the neutering compared to GPUBuffer.unmap.

    Doesn't solve @devshgraphicsprogramming's usecase.

    This usecase is described in this #481 (comment) copied below.

    For static data this doesn't matter, but applications often have dynamic data (uniforms, vertex, and index) and here are two usecases that buffer partitioning meant to address:

    • Having the dynamic data in CPU-GPU-visible, using some of it on the GPU while updating it on the CPU in a data-race-free manner. This is to have a single large allocation, and a path to update the data with a single copy (the CPU -> buffer copy).
    • Reducing GC pressure by using a single large uniform buffer in shared memory, so that all uniforms come from a different dynamic offset of the same buffer. (otherwise there would need to be a bindgroup per uniform buffer, which another dimension of bindgroup to create). The other constraint here is to update the uniform buffer with the one copy path, instead of a pipelined copyBufferToBuffer.

    This is because the staging memory is hidden behind the GPUUploadPass and the data always go through at least one staging->GPU copy before being available (vs. truly zero-copy for the usecases above). @kvark mentioned offline that we could do the copy for ranges we know aren't in use by the GPU but I don't see a realistic way to track this without immense overhead.

    As noted in #481 I don't think it is possible to address this usecase nicely so I don't want to hold GPUploadPass because of it.

    Alternative

    I think this proposal is in addition to buffer mapping, not instead of. This addresses the small staging area concern.

    For the issue about the validation pitfalls, I think it would make sense to have the GPUUploadPass merged inside GPUQueue. This is similar to #488 or the discussion about having GPUQueue.writeBufferData. The biggest difficulty would be to know when to neuter the ArrayBuffers. The most logical place would be on submit, but it would still make the neutering appear "far" from the function call that makes it happen.

    I don't have a great solution apart from Rust-like borrow semantics, or making the ArrayBuffer only available in a callback like so:

    queue. uploadBuffer(buffer, offset, size, (data)=> {
       doStuffWith(data);
    });
    // data is neutered now.
  8. litherum commented on Nov 11, 2019

    @litherum
    Contributor

    @kvark

    I think this is a good direction to pursue. In fact, I could see some evolution of this proposal replacing buffer mapping, instead of just augmenting it. (Or not - having both coexist would be fine too.)

    Some comments:

    1. Unless I'm misunderstanding, this shouldn't be called a pass. Passes execute on the GPU's timeline, but this one executes on the CPU's timeline. We should call it something else to make this distinction clear.
    2. There are two flavors to call this API with: one where the application gives an array buffer to the implementation, and one where the implementation gives an array buffer to the application. Only the latter needs the finish() call. The former shouldn't have the finish() call, because it's a) unclear what it means, and b) depending on what it does mean, might allow races between asynchronous uploads in the implementation and Javascript changing the contents of the array buffer out from under the implementation.
    3. Similarly, the two flavors should be separated into two distinct functions with different signatures.
    4. It's unclear what the benefit of opening a pass, and starting a whole bunch of transfers, then closing the pass has over a loop that opens a single pass, starts a transfer, and closes the pass, repeatedly. What's the purpose of the aggregation?

    I'll probably have more questions depending on the answers to these.

    I think one of the use cases is a simple application that just wants to upload an MVP matrix to a vertex shader every frame. Do you think you could write a snippet of what that use case would look like with this proposal? I'm particularly interested in where it's legal to open and close the pass, and how that interacts with the existing buffer lifecycle in a simple app.

    Thanks for writing this up! This is a good direction to be exploring.

  9. austinEng commented on Nov 12, 2019

    @austinEng
    Contributor

    My conclusions from this week's discussion are that

    1. We should make these queue operations. queue.uploadBuffer(...)
    2. The GPUUploadPass.finish() call makes the lifetime of the ArrayBuffer suballocations into the "staging belt" well-scoped. However, we can also just say that ArrayBuffers only live until the next call to queue.submit.
    3. We could make (UploadBuffer extends ArrayBuffer) queue.uploadBuffer(...) return a special ArrayBuffer with a finish() function OR a [ArrayBuffer, FinishFn] tuple.
      Calling finish() allows the implementation to begin doing the upload early instead of waiting and batching everything until queue.submit.
      • Note: @damyanp observed this still allows the "staging belt" to be a ring buffer because allocations are still FIFO and only live until the next queue.submit. FinishFn allows the upload to begin early, but the ring buffer allocations aren't rec recycled together until queue.submit is called.
      • We could either validate that FinishFn was called, or implicitly detach all ArrayBuffers on queue.submit
    4. As @litherum suggested, we should clearly separate the versions with/without the user-provided data.
    5. There's concern about CPU-GPU data races with returning directly-mapped GPU memory. For now, these upload functions should ensure that there is no data race possible. It can be an implementation decision whether to return directly-mapped GPU memory or a mapped shadow copy. Directly mapping the GPU memory could have heavy tracking cost, but is theoretically possible.

    Open question from @damyanp: Can we create a path where the web developer can ensure they don't allocate increasingly more staging memory? i.e. an Async version?

  10. kvark commented on Nov 14, 2019

    @kvark
    ContributorAuthor

    Thanks everyone for insightful feedback!

    @Kangz

    Encourages small staging areas.
    This is less efficient than batched copies that are possible with a smart "staging manager" in an application that uses GPUBuffer.mapWriteAsync where staging memory is updated all at once, and then small copies are pipelined with copyBufferToBuffer

    We are comparing a zero-copy path with N ArrayBuffer objects versus a path where everything is copied at least once, and you are saying it's going to be less efficient? The GPUUploadPass doesn't restrict you from doing exactly the same thing: upload the data once and issue a few copies. Even better, if you place your data locally in a buffer to begin with, you may not need any copies.

    An extra pass adds validation pitfalls

    Multi-threading concern is a real one. The idea is that a pass (or whatever we call it) is created, used and destroyed in a short burst, never blocking access to a queue for long.

    This is because the staging memory is hidden behind the GPUUploadPass and the data always go through at least one staging->GPU copy before being available (vs. truly zero-copy for the usecases above). @kvark mentioned offline that we could do the copy for ranges we know aren't in use by the GPU but I don't see a realistic way to track this without immense overhead.

    There is some miscommunication here. My original post explicitly describes the zero-copy scenario, and in the case @devshgraphicsprogramming described we'd still have a chance to implement the buffer range tracking in such a way that, when a part of a buffer is requested for GPU uploads, we can just expose it to the user if we know that this part isn't used by the GPU (as opposed to knowing that the whole buffer is not used by the GPU). We can have this optimization implemented transparently at any point without any changes to the user code.

    In my understanding, tracking buffer sub-ranges for usages is similar to tracking texture sub-resources, which we already do in wgpu-native. I don't share the skepticism about this being unrealistic.

    I think this proposal is in addition to buffer mapping, not instead of. This addresses the small staging area concern.

    Understood, and this is a bit different from @litherum and my preference. I don't think the mapping we have today would need to stay. But perhaps, at some point, we'd want to introduce real persistent mapping in a similar fashion (from security perspective) to how SharedArrayBuffer API exists today. In that case, powerful but hard to use persistently mapped buffers would complement the simple and convenient API that is proposed in this issue.

    @litherum

    Unless I'm misunderstanding, this shouldn't be called a pass.

    I don't hold the name too strongly. I agree that "pass" name does not provide the cleanest semantics here.

    Similarly, the two flavors should be separated into two distinct functions with different signatures.

    I think it's a fair suggestion, and it looks like @austinEng also agrees here. The functions that don't depend on finish() could be placed right on the GPUQueue.

    I'll try to write down an example as a follow-up.

  11. Kangz commented on Nov 14, 2019

    @Kangz
    Contributor

    @kvark

    But perhaps, at some point, we'd want to introduce real persistent mapping in a similar fashion (from security perspective) to how SharedArrayBuffer API exists today. In that case, powerful but hard to use persistently mapped buffers would complement the simple and convenient API that is proposed in this issue.

    Having persistent mappings that allow races between the CPU and the GPU breaks the strong portability guarantees of WebGPU so I don't think it should ever be in the core API. Also for multi-process implementations without support to map inside the content process (right only Android might allow for this) you'll need something like vkFlushMappedMemoryRanges so it's not just as simple as putting a SharedArrayBuffer that can race.

    In my understanding, tracking buffer sub-ranges for usages is similar to tracking texture sub-resources, which we already do in wgpu-native. I don't share the skepticism about this being unrealistic.

    Resource tracking is a CPU hot-path for APIs like D3D11 and OpenGL, texture subresource tracking is already complex and expensive enough so I think you won't want to implement buffer subrange tracking, especially since it is more complicated then for texture: it is a continuous range of bytes instead of a discrete but small amount of subresources. Also there are things that would prevent that optiimization: how do you track the range of a vertex buffer used by a drawIndirect? This makes the API less explicit and optimizations more opaque which isn't good for devs.

    We are comparing a zero-copy path with N ArrayBuffer objects versus a path where everything is copied at least once, and you are saying it's going to be less efficient? The GPUUploadPass doesn't restrict you from doing exactly the same thing: upload the data once and issue a few copies. Even better, if you place your data locally in a buffer to begin with, you may not need any copies.

    See above, I don't think the tracking of ranges of buffers used byt the GPU is practical so I believe we are comparing two paths with the same number of copies, just more ArrayBuffers for GPUUploadPass.

  12. kainino0x commented on Nov 14, 2019

    @kainino0x
    Contributor

    Also there are things that would prevent that optiimization: how do you track the range of a vertex buffer used by a drawIndirect? This makes the API less explicit and optimizations more opaque which isn't good for devs.

    @Kangz and I realized while chatting that all of these cases prevent the optimization:

    • drawIndirect: range of vertex buffer
    • drawIndexed: range of vertex buffer
    • drawIndexedIndirect: range of both index and vertex buffer

    which makes it mostly only useful for copy src and uniform (and storage and indirect). Uniforms are the most common case, but I think the amount of data in a uniform buffer is usually so small that an extra gpu-side copy would have trivial impact.

  13. kvark commented on Nov 14, 2019

    @kvark
    ContributorAuthor

    Have you considered extending our setVertexBuffer/setIndexBuffer API to work with full ranges instead of just offsets? I suggested that earlier in the discussion about vertex buffer fetches and security, and I think that such an API would be very useful to us implementing WebGPU while not too complex for users, especially if the "size" of the exposed vertex/index buffer is defaulted to "all buffer", e.g.

    void setVertexBuffer(unsigned long slot, GPUBuffer buffer, GPUBufferAddress offset, GPUBufferAddress size = 0); // 0 corresponding to the "rest of the buffer"

    With this in, we'd both have easier time securing the vertex buffer access, and tracking buffer usage in general.

  14. kainino0x commented on Nov 14, 2019

    @kainino0x
    Contributor

    IIRC, our robust buffer access guarantees would necessarily allow reads from anywhere in the buffer, not just the bound range. So, what I think would happen is: in this case, out-of-bound-range accesses would have very predictable results (they just read the appropriate offset into the unbound range) but without race prevention. Since we have limited ability to do validation even in a very common case (drawIndexed), it would become extra necessary to make sure developers don't accidentally rely on these accesses working.

  15. kvark commented on Nov 14, 2019

    @kvark
    ContributorAuthor

    it would become extra necessary to make sure developers don't accidentally rely on these accesses working

    Isn't this already the case with robust buffer access? returning a value from a different part of the buffer is still within the RBA guarantees. Also, what do you mean by "without race prevention"?

  16. 3 remaining items

  17. kvark commented on Nov 18, 2019

    @kvark
    ContributorAuthor

    Proposal version-2:

    interface GPUArrayBuffer: ArrayBuffer {
      // Detach the buffer from its underlying storage,
      // allowing the implementation to use the data.
      void detach();
    }
    
    dictionary GPUTextureDataLayout {
      u32 rowPitch;
      u32 imageHeight;
    };
    
    interface mixin GPUUploadQueue {
      // Returns the currently available staging space, in bytes.
      readonly attribute GPUBufferSize availableUploadSpace;
    
      // Request the `space` extra bytes of the upload space to be reserved
      // for the subsequent upload operations.
      void reserveUploadSpace(GPUBufferSize space);
    
      // Upload the CPU data into the specified destination buffer.
      void setBufferSubData(
        GPUBuffer destination,
        GPUBufferSize destinationOffset,
        GPUBufferSize size,
        ArrayBuffer sourceData,
        GPUBufferSize sourceOffset);
      );
    
      // Schedule an upload of data into a buffer, exposed by `GPUArrayBuffer`.
      GPUArrayBuffer uploadBuffer(
        GPUBuffer destination,
        GPUBufferSize destinationOffset,
        GPUBufferSize size,
      );
    
      // Upload the CPU data into the specified destination texture.
      void setTextureSubData(
        GPUTextureDataLayout layout,
        GPUTextureCopyView destination,
        GPUExtent3D size,
        ArrayBuffer sourceData,
        GPUBufferSize sourceOffset);
      );
    
      // Schedule an upload of data into a texture, exposed by `GPUArrayBuffer`.
      GPUArrayBuffer uploadTexture(
        GPUTextureDataLayout layout,
        GPUTextureCopyView destination,
        GPUExtent3D size);
    
      void copyImageBitmapToTexture(
        GPUImageBitmapCopyView source,
        GPUTextureCopyView destination,
        GPUExtent3D copySize);
    );
    
    GPUQueue includes GPUUploadQueue;

    Key differences:

    • there is no separate "pass" concept, everything is done on the queue. At the same time, the logic is nicely contained within a mixin
    • methods that take user data are separately called setXxx for clarity
    • there is a way to query the available "staging belt" memory and reserve more of it. This would allow for more predictable performance.

    All the non-finished GPUArrayBuffer objects are automatically detached on the first submit call.

  18. kainino0x commented on Nov 19, 2019

    @kainino0x
    Contributor
  19. kainino0x commented on Nov 19, 2019

    @kainino0x
    Contributor
  20. kvark commented on Nov 19, 2019

    @kvark
    ContributorAuthor

    Thinking about this some more, reserving/exposing the available staging space can't be that simple, since the space can be chunked. I think we can postpone this part for later.

    As for the overhead of ArrayBuffer, we had some discussions related to #501 with our JS team and concluded the following:

    1. Since the expected use pattern for ArrayBuffer objects returned by our transfer methods is linear (i.e. FIFO), we can make them very fast at the JS implementation level, at least in Gecko.
    2. Perhaps, more importantly, the worst case of users (e.g. Babylon.JS) requesting an ArrayBuffer for each object (they need to update uniform data for, when rendering) is not worth optimizing for. They have easy ways to work around the ArrayBuffer overhead if it occurs (which is yet to be seen):
      - by updating uniform data for more than one object at a time
      - by using the setXxx functions, which incur an extra copy that is negligible considering the size of a uniform update. In general, we'd recommend using the uploadXxx methods only for larger updates (rough estimation I got is 1K and up).

    Finally, an example of the application code:

    function drawMaterial(pass, queue, material) {
      let uniformOffset = 0;
      pass.setPipeline(material.pipeline);
      pass.setBindGroup(0, material.commandBindGroup);
      for (let drawable of material.drawables) {
        let data = drawable.uniformData;
        queue.setBufferSubData(material.uniformBuffer, uniformOffset, data.length, data, 0);
        pass.setVertexBuffer(0, drawable.vertexBuffer);
        pass.setBindGroup(1, material.uniformBuffer, [uniformOffset]);
        pass.draw(0, drawable.vertexBuffer.length);
        uniformOffset += data.length;
      }
    }

    Alternatively, the user could upload all the uniform data at once (to avoid a copy):

    function drawMaterial(pass, queue, material) {
      pass.setPipeline(material.pipeline);
      pass.setBindGroup(0, material.commandBindGroup);
    
      let uniformSize = material.drawables[0].uniformData.length;
      let wholeArrayBuffer = queue.uploadBuffer(material.uniformBuffer, 0, material.drawables.length * uniformSize);
      let wholeView = new Uint8Array(wholeArrayBuffer);
      let uniformOffset = 0;
      for (let drawable of material.drawables) {
        wholeView.set(new Uint8Array(drawable.uniformData), uniformOffset);
        uniformOffset += uniformSize;
      }
      wholeArrayBuffer.detach();
    
      uniformOffset = 0;
      for (let drawable of material.drawables) {
        pass.setVertexBuffer(0, drawable.vertexBuffer);
        pass.setBindGroup(1, material.uniformBuffer, [uniformOffset]);
        pass.draw(0, drawable.vertexBuffer.length);
        uniformOffset += data.length;
      }
    }
  21. kvark commented on Nov 19, 2019

    @kvark
    ContributorAuthor

    @kainino0x fwiw, I don't think multi-queue would make this proposal better, instantly.
    For example, the user requests to uploadBuffer on Queue-A. We detect that the GPU isn't using it at the moment, and we can map it directly, so we return an ArrayBuffer object that views right into the buffer memory. If the user starts to submit work that depends on that buffer to a Queue-B, we get CPU-GPU races and non-portable behavior.

    At the very least, when/if multi-queue is landing, we can reformulate the automatic detach rules as:

    • the GPUArrayBuffer gets automatically detached upon a submission that uses the target resource in any way, which may even be a submission to a different queue.
  22. Kangz commented on Nov 21, 2019

    @Kangz
    Contributor

    Thanks @kvark for the offline chat about this. It helped flesh out feedback to be much more presentable.

    First of all, I have no concerns with setBufferSubData or setTextureSubData except from details that don't matter at this stage of the proposal (naming, defaults, offset+size overloads).

    However the GPUUploadQueue methods returning ArrayBuffer have several unfortunate interactions (in order of most important to least important):

    • Multithreading. It is not possible to detach ArrayBuffers cross worker, so the question is what should happens if an ArrayBuffer is handed to the application for buffer and later buffer is used in a GPUQueue.submit on a different worker? We can't detach cross-worker so if this is allowed, there is a possibility of a data-race between the CPU and the GPU (CPU writing to the ArrayBuffer while the GPU uses the underlying buffer).
    • Multi-queue (if we decide to have that): what should happen if ArrayBuffer is handed to the application for buffer by queue1 and later, on the same worker, buffer is used for queue2.submit (queue1 !== queue2)? If we need to be able to detach the ArrayBuffer then it means that we need to check all the resources references by the submit, on the content process side of multiprocess implementations. Such state tracking is something we would really like to avoid in Chromium as it would be very expensive.
    • GC pressure: For the last several years WebGL developers have been extremely vocal that forced garbage creation in WebGL is something to avoid as much as possible. WebGPU already has some forced garbage creation for command encoding (and even buffer mapping, I have nightmares where WebGPU devs come with ptichforks because we decided to have the API like that). That Firefox's JS folks didn't seem too concerned is a surprise and we should get more data from other JS engines and the vocal WebGL developers.
    • Interaction between several upload commands: what should happen if multiple upload commands are used to write to the same bytes in the same block of upload commands (before the next submit)? Same question for mixed upload and setFooSubData. We could say they are resolved in order but is that the order of the calls, or the order of the GPUArrayBuffer.detach calls?

    If we want to allow GPUQueue to be used on multiple workers at the same time (that's important for example to have an upload thread), then the multi-threading interaction forces us to add some validation where uploadFoo's ArrayBuffers must be explicitly detached by the application before the GPUQueue.submit. This could work with an "uploading" state that's very similar to the "mapped" state we have for buffers in the current spec.

    Same conclusion with the multi-queue interaction. (or maybe we need a notion of resources being owned by a queue so you can only upload on resources owned by that queue, but quid of the ownership transfer interaction with uploadFoo?).

    Overall this makes the uploadFoo proposal more awkward than it first looked and there's still the concern about GC pressure.

    Extension to any mechanism allowing exposure of the staging belt

    With @kvark we wondered if there was another way to expose the staging belt that wouldn't have issues, and wouldn't be just giving the parts of the staging belt with mapWriteAsync (@kvark had concerns about mapWriteAsync requiring general allocators for the GPUBuffer when a belt should be enough). The problem is that with multi-threading (and multi-queue) it's hard to give an ArrayBuffer that's part of the belt and have a guarantee that it will be detached "soon" (aka next submit or same frame). The only way to do this would be to have the ArrayBuffer live only for the duration of a callback, but I don't think stuff like this has ever been done before in JS and produces even more garbage than uploadFoo:

    queue.withUploadArea(buffer, offset, size, (stagingArea) => {
        putUniformsIn(stagingArea);
    });
    
    // GPUQueue.withUploadArea would look like
    function withUploadArea(buffer, offset, size, callback) {
        stagingArea = getStagingBeltChunk(size);
        callback(stagingArea);
        enqueueCopy(stagingArea, buffer, offset);
        stagingArea.detach();
    }
    
  23. kvark commented on Nov 22, 2019

    @kvark
    ContributorAuthor

    Thank you for writing this down, @Kangz ! These are great concerns to discuss.

    Multi-queue: I don't think we can constructively discuss this, since we don't know how this is going to look like: how the ownership and synchronization would work between queues regardless of the mapping.

    GC pressure: I feel like this is going more and more into FUD territory. We are designing a web-first API, and objects are first-class in JS and WebIDL. If users are concerned about the costs of returning an ArrayBuffer, they should be using WASM to begin with, and we should be considering WASM API as first-class for achieving low-overhead rendering. This has not been the way our group operated so far, for better or worse.

    In order to resolve this constructively, we need more data, either from the history of WebGL feedback/reports, or from our own more complicated benchmarks/samples. We shouldn't say "allocating objects is scary", and instead we should be asking "how many objects we expect an application to create at most each frame?".

    Interaction between several upload commands: the queue naturally establishes the order in which the uploads are done, it doesn't depend on when detach() is called.

    Multithreading: I didn't realize that we can't detach an ABOs from a different thread. Requiring the users to do it is also adding some unwanted complexity: the implicit state of the buffer would need to be specified more concretely by the spec. If it all comes down to the problem of "we don't control when the user detaches the mapping", then working with a function/closure does sound like a solution to consider. We could specify that:

    • closures are guaranteed to be invoked in the order of queue upload commands
    • all closures are guaranteed to be resolved by the time the next submission is processed on the queue

    It doesn't sound too bad to me :)


    TL;DR: here is the full list of options to proceed

    1. accept the current API with zero-copy uploadXxx methods, using one of the following solutions:
      - require the user to detach explicitly before the next submission, or they get a validation error
      - user provides a closure, and we specify when it's expected to be resolved
    2. accept the current API without zero-copy methods, keep discussing how these would look like
    3. reject this API and think of something else
  24. kdashg commented on Nov 25, 2019

    @kdashg
    Contributor

    As an exercise, I drafted a polyfill for this:
    https://hackmd.io/@jgilbert/StockBeltUploader

    The main limitation is it can't handle zero-copy into "idle" buffers, which I think we'd need an API change (fallible mapIdle()?) to enable.

  25. kainino0x commented on Nov 27, 2019

    @kainino0x
    Contributor

    @kainino0x fwiw, I don't think multi-queue would make this proposal better, instantly.
    For example, the user requests to uploadBuffer on Queue-A. We detect that the GPU isn't using it at the moment, and we can map it directly, so we return an ArrayBuffer object that views right into the buffer memory. If the user starts to submit work that depends on that buffer to a Queue-B, we get CPU-GPU races and non-portable behavior.

    This doesn't seem unique to uploading. If you allowed that to happen then you would also allow GPU-GPU races between different queues, which of course we don't want. So some mechanism has to be in place to insert semaphores between queues, whether implicit or explicit, and we'd rely on that here too.

  26. litherum commented on Feb 24, 2020

    @litherum
    Contributor

    (In the context of the OP proposal, not "Proposal version-2")

    The transfer operations are queued on the queue at the GPUUploadPass::finish() time from the user perspective.

    I assume this means that it's illegal to submit command buffers to the queue between the time GPUQueue.beginUpload() is called and and GPUUploadPass.finish() is called? Otherwise, the browser doesn't know when it can fast-path an upload, because it doesn't know if the writes would have to be deferred until after some command buffer executes.

  27. litherum commented on Feb 24, 2020

    @litherum
    Contributor

    It looks like, if you take "Proposal version-2" and then remove the methods returning array buffers (because "However the GPUUploadQueue methods returning ArrayBuffer have several unfortunate interactions") you get something pretty close to #509. Maybe we can add the explicit staging belt facilities as a follow up, if we really need them?

    At any rate, if we're considering "Proposal version-2" instead of the OP proposal, it seems like we ought to start with #509 and add the additional pieces as we need them. If, on the other hand, we're considering the OP proposal, then I think my question about aggregation still stands.

  28. kvark commented on Feb 24, 2020

    @kvark
    ContributorAuthor

    @litherum

    I assume this means that it's illegal to submit command buffers to the queue between the time GPUQueue.beginUpload() is called and and GPUUploadPass.finish() is called?

    Right, if I remember correctly, that was the idea, and it was also one of the points of concern: if we consider the user to have multi-threaded submission, then it becomes easy to hit this accidentally when submitting from a different thread that does uploading.

    I believe #509 is a good concrete step here, and we can focus on it instead of pursuing the proposals of this issue. We can even close this.

  29. litherum commented on Feb 25, 2020

    @litherum
    Contributor

    We can even close this.

    Given @kvark is the OP, and says we can close this, and issues should be closed if they can be... closing now.

    Please feel free to re-open if you feel this was an error.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions