Skip to content

Synchronous non-blocking mapWrite #594

Closed

Description

@Kangz

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

  1. All browsers are or will be multiprocess.

  2. To have a pit of success, buffers are either upload buffers, readback buffers, or device-local buffers. This means that MAP_WRITE can only be used as COPY_SRC and MAP_READ only with COPY_DST. Allowing mappable usages with usages like VERTEX or UNIFORM means 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.

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

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 mapWrite after creation or an unmap call, 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 that GPUBuffer. (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 mapWrite allow specifying the full range, or only a subrange?
  • Is the content of the buffer cleared after the first mapWrite call after creation or unmap or 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

  1. kvark commented on Mar 6, 2020

    @kvark
    Contributor

    Thank you for writing this down @Kangz !

    The way I look at mapWrite proposal is as an expression of Managed buffer 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:

    1. It just avoids handling UMA efficiently. We want the API to work on mobile and integrated GPUs, UMA should not be an afterthought.
      - contrary to writeToBuffer it doesn't support writing directly into a buffer that is usable by GPU (i.e. you always work with a staging buffer).
    2. It doesn't explain what the contents of the returned ArrayBuffer are, 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.
    3. There is no proper "Possible implementatin" suggested. Creating a shmem for the whole buffer is not feasible on a first request, since we don't know how much we'll need.
    4. It forces the creation of ArrayBuffer objects, potentially in hot paths. Triggering garbage collection may introduce hitches.
    5. Last but not the least, the comparison with writeToBuffer is wrong... When the user gets an ArrayBuffer, there is one required copy of data into it. That means, all the counters for this proposal should be increased by 1. Contrary, with writeToBuffer it could easily be the case where the user already has the data ready (e.g. uniform data that doesn't change often).
  2. kenrussell commented on Mar 6, 2020

    @kenrussell
    Member

    Thank you for writing this down @Kangz !

    The way I look at mapWrite proposal is as an expression of Managed buffer 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:

    1. It just avoids handling UMA efficiently. We want the API to work on mobile and integrated GPUs, UMA should not be an afterthought.
      • contrary to writeToBuffer it doesn't support writing directly into a buffer that is usable by GPU (i.e. you always work with a staging buffer).

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

    1. It doesn't explain what the contents of the returned ArrayBuffer are, 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.

    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.

    1. There is no proper "Possible implementatin" suggested. Creating a shmem for the whole buffer is not feasible on a first request, since we don't know how much we'll need.

    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.

    1. It forces the creation of ArrayBuffer objects, potentially in hot paths. Triggering garbage collection may introduce hitches.

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

    1. Last but not the least, the comparison with writeToBuffer is wrong... When the user gets an ArrayBuffer, there is one required copy of data into it. That means, all the counters for this proposal should be increased by 1. Contrary, with writeToBuffer it could easily be the case where the user already has the data ready (e.g. uniform data that doesn't change often).

    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.

  3. kvark commented on Mar 9, 2020

    @kvark
    Contributor

    @kenrussell thank you for the quick response!

    First of all, I don't feel comfortable answering the points about mapWriteDirect since we haven't seen an actual proposal for them. Do you want to make one (either standalone, or by evolving this issue)?

    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.

    The beauty of writeToBuffer is that we don't have to answer the question if this is critical right now. We could just add a flag like MAP_WRITE_DIRECT later 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.

    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.

    We can't just pretend this cost is unavoidable though. It doesn't affect writeToBuffer for 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 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.

    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.

    writeToBuffer induces an additional data copy between the content and GPU process which must be traded off with this ArrayBuffer allocation.

    I respectfully disagree. The writeToBuffer may 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 their ArrayBuffer, doesn't change often, and they can at any point handle that to us without copying.

    ArrayBuffer objects' allocation and reclamation should be optimized by JavaScript VM implementers so they are cheap.

    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.

    The application will ideally produce its data directly into the ArrayBuffer returned by mapWrite. It depends on its internal structures.

    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 explicit APIs are phrased around map/unmap operations rather than OpenGL-like bufferSubData operations,

    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.

    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.

    Let's not assume but measure. So far, we can't even agree on how we are counting the copies :)

  4. austinEng commented on Mar 9, 2020

    @austinEng
    Contributor

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

    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 mapWrite is allowed for vertex buffers, etc. too).

    To be clear: mapWrite returns to the user a piece of staging shmem that is visible to the GPU hardware. unmap issues a copy from that into the device-local buffer. On UMA, an implementation may do range tracking and directly map the buffer instead.

    At the same time, I can easily think of a use case where each entity of the user points to a sub-range of their ArrayBuffer, doesn't change often, and they can at any point handle that to us without copying.

    In terms of number of copies, if the user already has an ArrayBuffer, then the proposals should be equivalent in number.

    • writeToBuffer (UMA w/ tracking): user-ArrayBuffer --> GPUBuffer
    • mapWrite (UMA w/ tracking): user-ArrayBuffer --> mapping of GPUBuffer returned by mapWrite
    • writeToBuffer (staged): user-ArrayBuffer --> staging --> GPUBuffer
    • mapWrite (staged): user-ArrayBuffer --> staging returned by mapWrite --> GPUBuffer

    However, if the user doesn't already have data in an ArrayBuffer and is decoding or streaming data into the mapping, then mapWrite offers fewer copies.

    We can't just pretend this cost is unavoidable though. It doesn't affect writeToBuffer for 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.

    Fair point, but we should measure this. I'd be surprised if a memset is going to be that bad.

    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.

    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 writeToBuffer is our best option for synchronous updates.

  5. JusSn commented on Mar 9, 2020

    @JusSn
    Contributor

    Closing this as discussed in 3/9/2020 meeting

  6. kainino0x commented on Mar 14, 2020

    @kainino0x
    Contributor

    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.

    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 respectfully disagree. The writeToBuffer may 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 their ArrayBuffer, doesn't change often, and they can at any point handle that to us without copying.

    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.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions