Skip to content

Resource Round-Robining #38

Closed
Closed

Description

@litherum

Background

On Nov. 1, there was consensus in the group about scheduling resource uploads & downloads at a particular point in the device's queue so that the CPU and GPU wouldn't be accessing the same resource at the same time. This is the best (only?) solution for resources which live across multiple frames.

Let's consider the other side of the issue: when information on the CPU is only necessary on the GPU for a single frame. One example of this is the Model View Projection matrices, which are consistent throughout a single frame, but will change from frame to frame.

There are a few possible models for these kinds of resources:

  1. Resource Churn The application allocates and destroys a new resource each frame. Obviously (I think we can all agree) we don't want this.
  2. Scheduled Uploads The application uses a single resource, and schedules an upload at the start of each frame.
  3. Explicit Recycling Allocate n resources up front, and recycle them each frame. We can piggyback off the design of the swapchain here, because the swapchain includes n buffers, and it guarantees that, when you're recording commands to draw into a particular swapchain buffer, that buffer is not being accessed by the GPU. If we make an array of our own resources which parallels the n buffers in the swapchain, the parallel item in our own resource array is unused by the GPU at recording time, and therefore is free for the CPU to populate.
  4. Implicit recycling Just like above, a collection of resources will be created, but this array is owned by the implementation. All resources exist inside the implementation in a "free pool" or an "in-use pool." When an application asks for a resource, one is pulled from the free pool, or if the pool doesn't contain anything compatible, a new one is created. The application then attaches this resource to their recording commands, and notifies the implementation when they're done recording with this resource. At this point, however, the resource isn't returned to the free pool; instead, the implementation only returns the resource to the free pool when the GPU is finished with the resource. This way, any resource granted to the application is free to be immediately written into by the CPU. (Indeed, the resource acquisition function may even accept an argument to specify the resource's initial contents.) In this option, the same number of resources will be created and recycled as in option 3, but the application doesn't own the array.

Recommendation

Option 4 is most compatible with a Web API, and should be the model for WebGPU. This is for a few reasons.

Option 2 is a good start, but we can do better. In this model, the CPU-side memcpy() will occur on the GPU's timeline, taking time away from the GPU's execution. The other models allow for issuing the memcpy() during command recording, before ownership of the resource has been given to the GPU.

Option 3 improves upon 2, but has the drawback of making application logic dependent on the number of buffers in the swapchain, which is another potential source of non-portability. In particular, both Metal and Vulkan (and maybe Direct3D, I don't know) don't let the application specify exactly how many buffers the swapchain contains. Vulkan allows the application to request a certain number, but the actual implementation may return a different number than requested. Metal never tells you how many buffers are in the swapchain, but just gives you the "next one." We'd like to avoid web authors hardcoding a constant number of resources in their application because that happened to be how many buffers their local machine was using.

Option 4 has all the benefits of option 3, but has additional benefits:

  1. Portability Application logic is insensitive to the number of buffers in the platform's swapchain.
  2. Performance Letting the browser automatically recycle resources means that the browser can improve the performance of poorly-written applications. Recycling should be automatic; developers shouldn't have to opt-in to good performance.
  3. Fingerprinting The nature of the platform swapchains would provide more entropy for fingerprinting.

Activity

  1. Kangz commented on Nov 2, 2017

    @Kangz
    Contributor

    Updated the title to "Resource round-robining", let me know if this isn't what you wanted the issue about.

    1. Yeah... let's not do that.
    2. This is a pretty good option in the cases where we can take advantage of parallelism between the copy queue and graphics queue.
    3. I assume that when you mean explicit allocation, it is from the application? I believe this is how most high-performance games do things. The WebGPU implementation could guarantee that you need at most triple buffering if you use requestAnimationFrame.
    4. Isn't this implementable on top of 3) as a small helper library? The goal of WebGPU isn't to make graphics on the Web foolproof, it is to make it efficient and portable.

    Overall I think letting applications do 3) on their own or with a library is best, with an option for 2) if we have explicit queues.

    I'm not sure what's the link with swapchains but having a "get next texture" for them is ok. That's what we currently have in NXT and helps smooth the difference between different environments.

  2. changed the title [-]Resource Lifetime Management[/-] [+]Resource Round-Robining[/+] on Nov 2, 2017
  3. litherum commented on Nov 2, 2017

    @litherum
    ContributorAuthor

    The facilities in option 2 are needed for changing the contents of a resource which lives across multiple frames. Our API needs to have these facilities. This issue is about providing an additional mechanism for uploads for data which is only relevant for a single frame.

    I'll try to be more specific about the distinction between options 3 and 4.

    Here is what the WebGPU application's pseudocode would look like for option 3:

    let MVPs = [];
    let bufferCount = 0;
    let currentBufferIndex = 0;
    
    function setup() {
        bufferCount = swapChain.getNumberOfBuffers();
        for (let i = 0; i < bufferCount; ++i)
            MVPs[i].push(device.createBuffer());
    }
    
    function drawASingleFrame() {
        MVPs[currentBufferIndex].populateWith(data);
        attachBufferToActiveResources(MVPs[currentBufferIndex]);
        draw();
        currentBufferIndex = (currentBufferIndex + 1) % bufferCount;
    }

    And the pseudocode for option 4:

    function drawASingleFrame() {
        let MVP = device.pullFromFreeListAndPopulateWith(data);
        attachBufferToActiveResources(buffer);
        draw();
        device.ImDoneWith(buffer);
    }

    You can see that option 4 is much easier to write, has the same (or better!) performance characteristics, and doesn't expose sensitive information about the underlying platform to the webpage. A developer can't mess up the setup() function by hardcoding a 3 instead of swapChain.getNumberOfBuffers().

  4. litherum commented on Nov 2, 2017

    @litherum
    ContributorAuthor

    Actually, now that I think about it, the MVPs[currentBufferIndex].populateWith(data); in the above example doesn't work anyway, because that isn't associated with a particular point in the queue. And, once you associate it with a point in the queue, you've now devolved to option 2.

  5. kainino0x commented on Nov 2, 2017

    @kainino0x
    Contributor

    In Vulkan, and in NXT, there are Push Constants, which seem basically designed for the MVP matrix use case. They're very simple to use, and I think that on APIs which don't support them natively the implementation will look very similar to Option 4.

  6. litherum commented on Nov 2, 2017

    @litherum
    ContributorAuthor

    @kainino0x Yep, both Vulkan and D3D12 have this concept, and if this concept was exposed as part of the WebGPU API, the implementation on Metal would look similar to option 4.

    I opened this issue to propose a new mechanism for data uploads, and I think an API mechanism like push constants could fit. There are two issues that we would have to work out, though:

    1. IIRC push constants and root constants are required to be quite small, and "small" is platform-dependent. We would probably want this feature to work with larger resources, so the WebGPU API would probably have to automatically promote push constants to real buffers if they're too big (or, inversely, "promote" to push constants if the data is small enough. This would give us an automatic performance win).
    2. Push constants and root constants are read-only. We probably would want to support writing to these objects. An example use case would be an algorithm which requires scratch space (off the top of my head, some OIT algorithms). For these algorithms, each frame's scratch buffer is independent from the other buffers, but they do need to be writable. Vulkan implementations could handle this automatically because all implementations already going to be parsing every shader at pipeline state creation time, so we will know if a resource will be written to. Therefore, we can promote to buffers if the shader writes to the resource.
  7. kainino0x commented on Nov 2, 2017

    @kainino0x
    Contributor

    Your argument 2 is quite interesting, and definitely not solved by the push constant/root constant feature. However I'd generally avoid adding in a new feature and making the API more complex.

    I'm not necessarily convinced that we need anything more than triple buffering, which I really think is quite simple compared to the rest of the size of any engine. A triple-buffer-but-only-when-you-need-it helper class should be a pretty small chunk of JS(/C/C++) that an app developer could reuse everywhere they need it.

    Do you think there's something here that the browser can do better than a helper library can?

  8. litherum commented on Nov 2, 2017

    @litherum
    ContributorAuthor

    Do you think there's something here that the browser can do better than a helper library can?

    Yes. The browser knows how many buffers the swapchain holds, and therefore the number of duplicate resources that need to be created if each draw call needs access to an independent resource. The webpage should not know how many buffers the swap chain holds.

    As an aside, I think there's a point above that I didn't make clearly: The existing scheduled writes that we all agree on is sufficient (from an expressiveness point-of-view) for all use cases. MVP matrices or scratch buffers can be created and written using scheduled writes (option 2), and the web content doesn't know how many buffers the swapchains hold. I opened this issue to try to come up with a second mechanism which would improve performance in some situations. This second mechanism isn't a requirement, it's just a nice-to-have.

  9. kainino0x commented on Nov 3, 2017

    @kainino0x
    Contributor

    Okay, it sounds like we can decide post-mvp. Maybe we should start labelling issues once we decide whether they're pre- or post- mvp.

    Although this may have some bearing on what kind of information the API provides about memory allocations (part of the other issue).

  10. Kangz commented on Nov 3, 2017

    @Kangz
    Contributor

    Agreed that push-constants aren't a good fit because they are very small and read-only.

    Yes. The browser knows how many buffers the swapchain holds, and therefore the number of duplicate resources that need to be created if each draw call needs access to an independent resource. The webpage should not know how many buffers the swap chain holds.

    I'm not sure I follow the link between the number of images of the swapchain and round-robining. Swapchains textures are used to buffer with the display, but the browser is in control of how many frames or rendering are in flight at any given time (through GPU-CPU sync points) so it could make sure there are always at most 2 frames in flight, which makes only 3 resource copies necessary for round-robining.

    Application code can be the following:

    let availableMVPs = [];
    let inFlightMVPs = []
    let fences = []
    
    function setup() {
        for (let i = 0; i < 3; ++i)
            availableMVPs.push(device.createBuffer());
        }
    }
    
    function checkFences() {
        while (fences.length > 0 && fences[0].signaled) {
            fences = fences.slice(1);
            availableMVPs.push(inFlightMVPs[0]);
            availableMVPs = availableMVPs.slice(1);
        }
    }
    
    function drawASingleFrame() {
        checkFences();
    
        // This condition should never be hit
        if (availableMVPs.length == 0) {
            availableMVPs.push(device.createBuffer());
        }
        let mvp = availableMVPs.pop();
    
        mvp.populateWith(data);
        attachBufferToActiveResources(mvp);
        draw();
    
        inFlightMVPs.push(mvp);
        let fence = new Fence();
        queue.signal(fence);
        fences.push(fence);    
    }
  11. kvark commented on Nov 6, 2017

    @kvark
    Contributor

    @litherum

    There are a few possible models for these kinds of resources:

    I believe it's missing an extra option that works good for stuff like MVP matrices:
    5. Update GPU data by in-lining updates in the command buffer

    See vkCmdUpdateBuffer for more info. Basically, the user schedules an update of a GPU resource at some point in the command buffer, which means none of recycling/extra copies/scheduling (expressed in points 1-4) are necessary.

    This method would be very handy, although it is applicable for small-ish updates (up to 64k in Vulkan). For bigger resources, I believe giving control to the user would be best, since we can't afford allocating more copies than necessary, and the user knows best how many are needed.

  12. devshgraphicsprogramming commented on Nov 14, 2018

    @devshgraphicsprogramming

    We tackled a similar issue in our engine.

    Every update goes through a staging buffer, although you can write to a staging buffer directly (insecure).

    The staging bufffer is like an allocator+heap, except that the frees happen like Garbage Collection through a Deferred GPU Event handler.

    Every staging buffer memory free gets associated with a GPU fence (in Vulkan parlance, an event) and the free actually gets executed when the event signals.
    When the allocator (staging buffer) tries to allocate it will poll the events if it has low free space while allocating.

    This is the highest performance way of doing updates, except for when you want to update host-side API buffers.

  13. magcius commented on Nov 14, 2018

    @magcius

    Plenty of resources will change between frames besides modelviewprojection matrices (anything animating, e.g. texture or bone SRTs, color animations, blend shapes, visibility). Push constants aren't a general solution.

    I'm using option #2 in my prototype right now, but I would be OK with implementing #3 in my code. Adding more functionality to the WebGPU layer to buffer updates is bad. e.g. Often times, when building velocity buffers, you want to have a read-only copy of the animation or mvp matrices from last frame anyway, so users are going to be buffering them themselves. Having it hidden behind implementation details is just going to have apps waste more memory.

  14. devshgraphicsprogramming commented on Nov 14, 2018

    @devshgraphicsprogramming

    I agree explicit is best.

  15. litherum commented on Jan 9, 2021

    @litherum
    ContributorAuthor

    I believe WebGPU uses option #4. (The evidence is that I don't believe the number of buffers in the swap chain is exposed, which means #3 is impossible.) So I think this issue can be closed.

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