Repository navigation
Description
Behold another data upload proposal! It comes from lengthy discussions internally with @austinEng (basically a simplification of his idea) @kenrussell with input from @kvark and @kainino0x (actually close to one of his very old proposals).
Assumptions
-
All browsers are or will be multiprocess.
-
To have a pit of success, buffers are either upload buffers, readback buffers, or device-local buffers. This means that
MAP_WRITEcan only be used asCOPY_SRCandMAP_READonly withCOPY_DST. Allowing mappable usages with usages likeVERTEXorUNIFORMmeans developers are likely to think "great, I can have all the usages at once", have it work OK on their Intel laptop but be much slower on discrete GPUs. Having all buffers mapped or mappable also adds more pressure to the OS, even on mobile. I think it's better to allow known universal fast paths (that can prevent some last % optiimzations) and have an optional feature for UMA, or a more expert feature for reduced restrictions on mappable buffers. -
In a large amount of systems it will be possible to synchronously create a shmem in the content process, and send it to the GPU process where it will be wrapped in a GPU resource. This is possible:
- on D3D12 with ID3D12Device3::OpenExistingHeapFromFileMapping
- on Metal with MTLDevice newBufferWithBytesNoCopy:length:options:deallocator:
- on Vulkan with VK_EXT_external_memory_host
- on Vulkan Android with AHardwareBuffer magic when the extension is not supported.
Proposal
mapReadAsync stays the same. MAP_WRITE (resp. MAP_READ) is only allowed with COPY_SRC (resp. COPY_DST). GPUBuffer now includes the following methods for mapping related things:
partial interface GPUBuffer {
ArrayBuffer mapWrite(unsigned long offset = 0, unsigned long size = 0);
async ArrayBuffer mapReadAsync();
void unmap();
};Calling mapWrite puts the buffer in the "mapped for writing" state. It's a validation error (and JS exception?) to mapWrite overlapping ranges of the buffer (until the next unmap). As usual it's an error to call GPUQueue.submit with a buffer in the mapped state referenced in the commands argument.
mapWrite returns a new ArrayBuffer that will replace the content of that range of the buffer when unmap is called. There's also some restrictions where a buffer can only be mapped on one thread and has to be unmapped there. (that's eww compared to native :/, maybe we can find something better).
Possible implementation
An example implementation of this proposal could be that:
- On the first
mapWriteafter creation or anunmapcall, a shmem of the same size as the buffer is created and returned to JS. At the same time it is sent to the GPU process and wrapped in a GPU resource there that replaces the previous GPU resource associated with thatGPUBuffer. (replacing the resource is mostly ok because of the usage restrictions) - On unmap, a signal is sent to the GPU process that the data has been unmapped (for submit validation).
If the OS / driver doesn't support wrapping shmem in GPU resources, unmap() sends a list of regions from the shmem to update in the mapped buffer.
Imagine we are a really smart user-agents that knows which sub-ranges of a buffer are in use on the client side, then we can skip creating a new shmem and reuse the existing one.
Choices
- Does
mapWriteallow specifying the full range, or only a subrange? - Is the content of the buffer cleared after the first
mapWritecall after creation orunmapor is the buffer content preserved? - More stuff I missed?
Comparison with writeBuffer
In the case where we can wrap shmem in a GPU resource, the number of copies for writeBuffer / mapWrite for JS and WASM are the following:
- JS
mapWrite:shmem/staging -> device-local - WASM
mapWrite:wasm -> shmem/staging -> device-local - JS
writeBuffer:data -> shmem/staging -> device-local - WASM
writeBuffer:data -> shmem/staging -> device-local
When it's not possible to wrap shmem, the shmem/staging step becomes shmem -> staging with one extra copy happening.
mapWrite in JS is the fastest path and it incurs a single copy after initialization of the data. All other paths need to copy from some already initialized data somewhere to shmem and incur 2 copies. At some point I thought WASM writeBuffer would be better than WASM mapWrite but that turned out to not be the case.
A reason for doing writeBuffer is for simplicity, but I think that mapWrite is fairly understandable and can easily shim writeBuffer (more easily than mapWriteAsync for example).
Activity
kvark commentedon Mar 6, 2020
Thank you for writing this down @Kangz !
The way I look at
mapWriteproposal is as an expression ofManagedbuffer type of Metal API. You have means to synchronize parts of the buffer from CPU to GPU when you want. It's fairly elegant in this way.Overall, however, I have many concerns about this approach:
- contrary to
writeToBufferit doesn't support writing directly into a buffer that is usable by GPU (i.e. you always work with a staging buffer).ArrayBufferare, just mentions this choice. I believe it's important and affects the performance characteristics of the approach. I.e. zeroing out the contents is pretty much a half-copy, and it may thrash the CPU data cache.ArrayBufferobjects, potentially in hot paths. Triggering garbage collection may introduce hitches.writeToBufferis wrong... When the user gets anArrayBuffer, there is one required copy of data into it. That means, all the counters for this proposal should be increased by 1. Contrary, withwriteToBufferit could easily be the case where the user already has the data ready (e.g. uniform data that doesn't change often).kenrussell commentedon Mar 6, 2020
@Kangz @austinEng and I discussed integrating a fallible "mapWriteDirect" entry point into this proposal, following @jdashg 's fallible buffer mapping proposal, and a new usage flag like MAP_WRITE_DIRECT. Only buffers allocated with that usage flag and properly synchronized upon would be able to be directly mapped, otherwise null would be returned. In multiprocess browsers, it's likely those buffers would be persistently mapped cross-process all the time, and views into that persistent mapping provided as ArrayBuffers. This supports the UMA use case.
This requires fairly complicated range tracking on both the content and GPU process sides to detect data races, and we weren't confident that it wouldn't induce a significant performance hit to hot paths in the WebGPU API. It was for this reason that this isn't included in the proposal above, though we would like to collaborate on adding it if this is a critical requirement from your standpoint. If it can be considered a follow-on, we would like to suggest this initial solution first.
The suggested mapWriteDirect could be specified to potentially return data already in the buffer, but mapWrite must provide consistent results. JavaScript specifies that ArrayBuffers are zero-initialized, so this is a consistent default, and one whose performance hit is already accepted on the web platform.
The shared memory segments are expected to be the size of the requested mapping. These allocations are typically pooled, so they can be quickly and immediately returned without any cross-process round-trips.
writeToBufferinduces an additional data copy between the content and GPU process which must be traded off with this ArrayBuffer allocation. At least, for large amounts of data being uploaded per-frame to the GPU, eliminating the copy should be the higher priority. ArrayBuffer objects' allocation and reclamation should be optimized by JavaScript VM implementers so they are cheap. (They typically have non-trivial destruction, meaning that young generation GC can not trivially scavenge them - but nonetheless, effort should be expended on optimizing this rather than changing the API design to fit limitations of any current JavaScript VMs.)The application will ideally produce its data directly into the ArrayBuffer returned by mapWrite. It depends on its internal structures. Native explicit APIs are phrased around map/unmap operations rather than OpenGL-like bufferSubData operations, and it's reasonable to assume that JavaScript applications using WebGPU may be able to achieve better efficiency with these mapping operations rather than a writeToBuffer primitive.
kvark commentedon Mar 9, 2020
@kenrussell thank you for the quick response!
First of all, I don't feel comfortable answering the points about
mapWriteDirectsince we haven't seen an actual proposal for them. Do you want to make one (either standalone, or by evolving this issue)?The beauty of
writeToBufferis that we don't have to answer the question if this is critical right now. We could just add a flag likeMAP_WRITE_DIRECTlater specifying that writing to buffers with this flag would make the implementation to try to write the data directly instead of pipelining it. This wouldn't change any of the API other than an extra flag at buffer creation.We can't just pretend this cost is unavoidable though. It doesn't affect
writeToBufferfor example. Zeroing out all the staging memory is extra work, it costs CPU cycles, it may negatively affect the CPU data cache, and most importantly - in most cases it'd be wasted work. I don't feel good about just accepting it.The issue proposal needs to be redacted to express them. Right now it says "On the first mapWrite after creation or an unmap call, a shmem of the same size as the buffer is created and returned to JS". The other part ("At the same time it is sent to the GPU process and wrapped in a GPU resource there that replaces the previous GPU resource associated with that GPUBuffer") also may be trickier when we are talking about sub-ranges, since we are no longer replacing the whole resource.
I respectfully disagree. The
writeToBuffermay involve a copy. At the same time, I can easily think of a use case where each entity of the user points to a sub-range of theirArrayBuffer, doesn't change often, and they can at any point handle that to us without copying.When we were discussing the queued transfers proposal, GC pressure was a concern (see #491 (comment)). Moreover, in a bigger picture, I'd like us to try making it possible for the user to not have any GC interaction if they want to (edit: which would help VR latency-sensitive applications). The feedback I got from WebAudio group is that it doesn't matter if your objects are small, it only matters that you give GC a chance to freeze the world to inspect other allocations, which is undesirable. So it would be good to not add an entry point to the API where one has to create a new object.
Right. How is this not a copy then? The user goes through all the data, reads it from somewhere and writes it in our
ArrayBuffer. Every time they need to update the data. That sounds more heavy than a simple memcopy would be.Native APIs also have persistent mapping, push constants and inlined command buffer updates - none of them are exposed by us. We are also creating a new API specifically because we initially determined that the existing ones are no fit.
Let's not assume but measure. So far, we can't even agree on how we are counting the copies :)
austinEng commentedon Mar 9, 2020
Given that you can map subranges, I do agree that this proposal cannot make a shmem the size of the buffer and entirely replace the resource. I think it should suballocate a shmem exactly the size of the mapping and copy into the resource. This also means that the usage restriction can be lifted (so the rest of this comment will assume synchronous
mapWriteis allowed for vertex buffers, etc. too).To be clear:
mapWritereturns to the user a piece of staging shmem that is visible to the GPU hardware.unmapissues a copy from that into the device-local buffer. On UMA, an implementation may do range tracking and directly map the buffer instead.In terms of number of copies, if the user already has an
ArrayBuffer, then the proposals should be equivalent in number.However, if the user doesn't already have data in an
ArrayBufferand is decoding or streaming data into the mapping, thenmapWriteoffers fewer copies.Fair point, but we should measure this. I'd be surprised if a memset is going to be that bad.
I do agree that GC pressure is a concern, and it's frustrating to design around it. If we don't have some way of ArrayBuffer recycling as @kvark once suggested, then perhaps
writeToBufferis our best option for synchronous updates.JusSn commentedon Mar 9, 2020
Closing this as discussed in 3/9/2020 meeting
kainino0x commentedon Mar 14, 2020
It doesn't count as a copy for one-time uploads where you might even throw away the source data immediately afterward. The most obvious case of this is going from a gzip, jpeg, or basis universal compressed texture, into a buffer for upload.
I'm interested but don't quite understand. We would have to make sure any reading of the user's ArrayBuffer occurs during the writeToBuffer call, which is only possible if what we're doing during that call, synchronously, is an upload directly to the necessary GPU memory.
Trim redundant message from stack (for Chrome), clarify stack hiding (g…