Repository navigation
Description
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
magcius commentedon Nov 7, 2019
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.
kainino0x commentedon Nov 8, 2019
So far I really like this idea. I think it's a big improvement on the past proposals for upload passes.
Does
beginUploadneed to be async so that the gpu has a chance to finish using some things?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.
magcius commentedon Nov 8, 2019
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.
kainino0x commentedon Nov 8, 2019
I was thinking multi-queue would be the right solution to that problem. Do you think it would work?
kvark commentedon Nov 8, 2019
@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.
austinEng commentedon Nov 8, 2019
I like this idea as well!
I don't think it would be
beginUpload, but maybeuploadBufferAsyncwith noGPUUserDataprovided. 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.Kangz commentedon Nov 11, 2019
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
GPUUploadPassEncourages 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 smallArrayBuffers. This is less efficient than batched copies that are possible with a smart "staging manager" in an application that usesGPUBuffer.mapWriteAsyncwhere staging memory is updated all at once, and then small copies are pipelined withcopyBufferToBufferAn 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.SubmitandGPUQueue.writeToBuffer(if we have it) that is atomic w.r.t. the validation state tracking.Also it makes it less clear when
ArrayBuffersare neutered, if it is onfinishorGPUQueue.submitthere is less a correlation between the methods and the neutering compared toGPUBuffer.unmap.Doesn't solve @devshgraphicsprogramming's usecase.
This usecase is described in this #481 (comment) copied below.
This is because the staging memory is hidden behind the
GPUUploadPassand 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
GPUploadPassbecause 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
GPUUploadPassmerged insideGPUQueue. This is similar to #488 or the discussion about havingGPUQueue.writeBufferData. The biggest difficulty would be to know when to neuter theArrayBuffers. 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
ArrayBufferonly available in a callback like so:litherum commentedon Nov 11, 2019
@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:
finish()call. The former shouldn't have thefinish()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.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.
austinEng commentedon Nov 12, 2019
My conclusions from this week's discussion are that
queue.uploadBuffer(...)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 toqueue.submit.(UploadBuffer extends ArrayBuffer) queue.uploadBuffer(...)return a special ArrayBuffer with afinish()function OR a[ArrayBuffer, FinishFn]tuple.Calling
finish()allows the implementation to begin doing the upload early instead of waiting and batching everything untilqueue.submit.queue.submit.FinishFnallows the upload to begin early, but the ring buffer allocations aren't rec recycled together untilqueue.submitis called.FinishFnwas called, or implicitly detach all ArrayBuffers onqueue.submitOpen 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?
kvark commentedon Nov 14, 2019
Thanks everyone for insightful feedback!
@Kangz
We are comparing a zero-copy path with N
ArrayBufferobjects versus a path where everything is copied at least once, and you are saying it's going to be less efficient? TheGPUUploadPassdoesn'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.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.
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.
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
SharedArrayBufferAPI 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
I don't hold the name too strongly. I agree that "pass" name does not provide the cleanest semantics here.
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 theGPUQueue.I'll try to write down an example as a follow-up.
Kangz commentedon Nov 14, 2019
@kvark
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
vkFlushMappedMemoryRangesso it's not just as simple as putting aSharedArrayBufferthat can race.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.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
ArrayBuffersforGPUUploadPass.kainino0x commentedon Nov 14, 2019
@Kangz and I realized while chatting that all of these cases prevent the optimization:
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.
kvark commentedon Nov 14, 2019
Have you considered extending our
setVertexBuffer/setIndexBufferAPI 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.With this in, we'd both have easier time securing the vertex buffer access, and tracking buffer usage in general.
kainino0x commentedon Nov 14, 2019
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.
kvark commentedon Nov 14, 2019
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"?
3 remaining items
kvark commentedon Nov 18, 2019
Proposal version-2:
Key differences:
setXxxfor clarityAll the non-finished
GPUArrayBufferobjects are automatically detached on the firstsubmitcall.kainino0x commentedon Nov 19, 2019
kainino0x commentedon Nov 19, 2019
kvark commentedon Nov 19, 2019
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:ArrayBufferobjects 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.ArrayBufferfor each object (they need to update uniform data for, when rendering) is not worth optimizing for. They have easy ways to work around theArrayBufferoverhead if it occurs (which is yet to be seen):- by updating uniform data for more than one object at a time
- by using the
setXxxfunctions, which incur an extra copy that is negligible considering the size of a uniform update. In general, we'd recommend using theuploadXxxmethods only for larger updates (rough estimation I got is 1K and up).Finally, an example of the application code:
Alternatively, the user could upload all the uniform data at once (to avoid a copy):
kvark commentedon Nov 19, 2019
@kainino0x fwiw, I don't think multi-queue would make this proposal better, instantly.
For example, the user requests to
uploadBufferon Queue-A. We detect that the GPU isn't using it at the moment, and we can map it directly, so we return anArrayBufferobject 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:
GPUArrayBuffergets automatically detached upon a submission that uses the target resource in any way, which may even be a submission to a different queue.Kangz commentedon Nov 21, 2019
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
setBufferSubDataorsetTextureSubDataexcept from details that don't matter at this stage of the proposal (naming, defaults, offset+size overloads).However the
GPUUploadQueuemethods returningArrayBufferhave several unfortunate interactions (in order of most important to least important):ArrayBufferscross worker, so the question is what should happens if anArrayBufferis handed to the application forbufferand laterbufferis used in aGPUQueue.submiton 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 theArrayBufferwhile the GPU uses the underlying buffer).ArrayBufferis handed to the application forbufferbyqueue1and later, on the same worker,bufferis used forqueue2.submit(queue1 !== queue2)? If we need to be able to detach theArrayBufferthen it means that we need to check all the resources references by thesubmit, 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.uploadcommands: what should happen if multipleuploadcommands are used to write to the same bytes in the same block of upload commands (before the nextsubmit)? Same question for mixeduploadandsetFooSubData. We could say they are resolved in order but is that the order of the calls, or the order of theGPUArrayBuffer.detachcalls?If we want to allow
GPUQueueto 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 whereuploadFoo'sArrayBuffersmust be explicitly detached by the application before theGPUQueue.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
uploadFooproposal 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 aboutmapWriteAsyncrequiring general allocators for theGPUBufferwhen 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 theArrayBufferlive 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 thanuploadFoo:kvark commentedon Nov 22, 2019
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:
It doesn't sound too bad to me :)
TL;DR: here is the full list of options to proceed
uploadXxxmethods, using one of the following solutions:- require the user to
detachexplicitly before the next submission, or they get a validation error- user provides a closure, and we specify when it's expected to be resolved
kdashg commentedon Nov 25, 2019
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.
kainino0x commentedon Nov 27, 2019
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.
litherum commentedon Feb 24, 2020
(In the context of the OP proposal, not "Proposal version-2")
I assume this means that it's illegal to submit command buffers to the queue between the time
GPUQueue.beginUpload()is called and andGPUUploadPass.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.litherum commentedon Feb 24, 2020
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.
kvark commentedon Feb 24, 2020
@litherum
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.
litherum commentedon Feb 25, 2020
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.
Add validation tests plan for Occlusion Query (gpuweb#491)