Skip to content

Investigation: Render Target Aliasing #63

Open

Description

@litherum

We've heard from the Metal team that aliasing render targets is important for memory use.

The Problem

Imagine a WebGPU application that renders to a texture, then reads from that texture to render into another texture, then reads from that other texture to render into yet another texture. Long chains like this are common in games with post-processing.

The flow would look like the following:

   [ ]
    | Renders into
    V
Texture A
    |
    | Renders into
    V
Texture B
    |
    | Renders into
    V
Texture C
    |
    | Renders into
    V
The screen

With the current design, the application code would look like:

let textureA = device.createTexture();
let textureB = device.createTexture();
let textureC = device.createTexture();

let targetA = createRenderPassDescriptor(textureA);
commandEncoder.beginRenderPass(targetA);
commandEncoder.draw();
commandEncoder.endRenderPass();

let targetB = createRenderPassDescriptor(textureB);
commandEncoder.beginRenderPass(targetB);
commandEncoder.attachResource(textureA);
commandEncoder.draw();
commandEncoder.endRenderPass();

let targetC = createRenderPassDescriptor(textureC);
commandEncoder.beginRenderPass(targetC);
commandEncoder.attachResource(textureB);
commandEncoder.draw();
commandEncoder.endRenderPass();

commandEncoder.attachResource(theScreen);
commandEncoder.attachResource(textureC);
commandEncoder.draw();
commandEncoder.endRenderPass();

queue.submit([commandEncoder]);

This approach means that textures A and C both exist in memory at the same time. However; they don't need to - they are never accessed at the same time. In fact, they should be able to live in the same region of memory.

This is important for mobile devices because they usually have big and fairly high density screens, but not that much memory. Therefore, wasting memory as big as a frame buffer is quite unfortunate.

An application often can't simply reuse the same resource in multiple places in their frame (meaning: textures A and C usually can't literally be the same resource), because the resources may be required to be different sizes or formats.

Solution A: The Vulkan-Subpass Metaphor

One way to solve this problem is for the application to submit to us a plan of what the inputs and outputs of every future render pass will be so that the browser can figure out which targets can be aliased. The application would have to do this at the beginning of each frame.

This approach is unfortunate for a few reasons:

  1. This is how Vulkan subpasses work, and we have heard from IHVs that applications usually don't use these facilities. We can only assume that lack of adoption wasn't an accident.
  2. A scene graph renderer may not know ahead of time exactly how the frame will be laid out. For example, upon encountering a particular node, the engine may realize that they need a temporary buffer (e.g. to blur something).
  3. Figuring out how to alias render targets is essentially the graph coloring problem, which is NP-complete. We don't want the browser to have to do this analysis.

Solution B: Heaps

This solution would look like

interface WebGPUTextureHeap {
    WebGPUTexture createTexture(WebGPUTextureDescriptor descriptor);
}

partial interface WebGPUDevice {
    WebGPUTextureHeap createTextureHeap();
}

And the application code would look like

let heap = device.createTextureHeap();
let textureA = heap.createTexture();
let textureB = device.createTexture(); // This one comes from the device because it shouldn't be shared with anything
let textureC = heap.createTexture();

[and the rest is all the same]

Here, any textures created from the same heap would be able to alias. This is effectively making the programmer provide the solution to the graph coloring problem at resource creation time.

However, this is unfortunate because a particular coloring is relevant to a particular frame, not a particular resource. Frame plans change over time as the scene graph changes, and forcing a particular coloring for the lifetime of the entire resource would lead to suboptimal utilization.

Solution C: Purgability

Recall that the runtime (browser) needs to be able to evict resources due to OS pressure without notifying the running WebGPU program. This means that a WebGPU texture isn't pinned to a specific address, and may be relocated by the runtime at any time, without the application knowing.

Therefore, the problem isn't about "aliasing," per se. A browser can freely move resources around wherever it wants, and if it moves a resource on top of another resource, the other resource's contents gets clobbered. If the application wasn't using that resource, then there is no problem.

In the example above, the only reason the browser has to keep all the resources around at the same time is because the application may suddenly decide to use all the textures as inputs in one additional draw call. Therefore, the browser doesn't know that a resource is able to be clobbered.

So, this solution would simply add a function on WebGPUTexture:

partial interface WebGPUTexture {
    void purge();
}

This lets the browser know that the application is done using a resource. A purged resource will be guaranteed to have all its contents reset to 0s, and, therefore, the browser is free to place other resources on top of it.

A purged resource may be used, just like normal, at any point after that, but doing so will un-purge the resource. Un-purging a resource forces the browser to move any resources located on top of it.

There is no undefined behavior because purging a resource will fill it with 0s at the time it's next read, even if no other resource was relocated on top of it.

So, using purgeability, the above example would become:

let textureA = device.createTexture();
let textureB = device.createTexture();
let textureC = device.createTexture();
...
// At the beginning, everything is purged
let targetA = createRenderPassDescriptor(textureA);
commandEncoder.beginRenderPass(targetA); // Un-purges target A
commandEncoder.draw();
commandEncoder.endRenderPass();

let targetB = createRenderPassDescriptor(textureB);
commandEncoder.beginRenderPass(targetB); // Un-purges target B
commandEncoder.attachResource(textureA);
commandEncoder.draw();
commandEncoder.endRenderPass();
textureA.purge();

let targetC = createRenderPassDescriptor(textureC);
commandEncoder.beginRenderPass(targetC); // Un-purges target C
commandEncoder.attachResource(textureB);
commandEncoder.draw();
commandEncoder.endRenderPass();
textureB.purge();

commandEncoder.attachResource(theScreen);
commandEncoder.attachResource(textureC);
commandEncoder.draw();
commandEncoder.endRenderPass();
textureC.purge();

queue.submit([commandEncoder]);

Notice that textures A and C are never un-purged at the same time, so the implementation is free to make them alias. However, if some surprising draw call comes along and uses them both at once, the implementation will happily de-alias them and continue on.

Activity

  1. dmikis commented on Jul 18, 2018

    @dmikis

    Recall that the runtime (browser) needs to be able to evict resources due to OS pressure without notifying the running WebGPU program.

    I'm interested in how such mechanisms look like in native APIs. As far as I know, there's no way for OS to notify an application about eviction of particular resources. There's only "lost device" concept that invalidates the whole set of previously created resources. Given that, the "...without notifying WebGPU program" part sounds like we're planning to handle at least some device loses in the browser without propagating it to WebGPU apps. Is it right?

  2. thomasdenney commented on Jul 19, 2018

    @thomasdenney

    I just had a look through this Frostbite presentation, which describes the concept of a FrameGraph, which was what they use for texture aliasing. I hadn't seen the presentation before, but I found a couple of interesting takeaways that will affect implementations:

    1. On slide 26 they state that they used a greedy algorithm for determining resource aliasing. My reading from the slides/presenter notes is that this is a greedy algorithm for graph coloring. They were doing this on fairly large graphs, so it may actually be viable to do this in an implementation.
    2. They also described the need for barrier synchronization when resources can alias. As a straightforward example, suppose that textures A and B can alias to some physical resource X, and that textures A and B are independently used by render passes 1 and 2 respectively, which are otherwise independent. To permit the alias, an implementation would need to ensure that the render passes can't simultaneously occur, even though they are otherwise independent. One implementation, suggested in the presentation, is to insert barrier synchronizations. The implementation could certainly choose when/where to insert these barriers, but I think minimizing the number of barriers is an independent problem to minimizing the number of physical resources. This problem is detailed on slides 46-50 of the presentation.
  3. litherum commented on Jul 20, 2018

    @litherum
    ContributorAuthor

    Another detail I should have mentioned is that all three approaches require zero-filling resources aggressively. This is for two reasons:

    1. The application should not dictate exactly what gets aliased and how. Instead, the application should provide some hints to the browser about what aliasing techniques may be a good idea, and the browser should figure out the best way to alias. The reason for this is given above: implementations need to have the freedom to move resources around (possibly off the GPU and back on) in order to be a good citizen of the OS. The website shouldn't be able to pin a resource on a specific place on the GPU forever.

    2. Because of portability and consistency, the details of exactly which resources the browser chose to alias should not be observable. We don't want to have authors write a program that is wrong, but happens to behave correctly on their development machine, just because their development machine happens to never alias.

    These two things, taken together, mean that we don't just have to zero-fill when resources happen to alias, but we also need to zero-fill when resources might alias.

    For example, in solution B, let's say your heap generates two textures, and you use one, and then use the other. If these resources alias, we need to zero-fill the memory between the two accesses so the second access doesn't get the undefined contents of the first resource. But, even if the implementation decided not to alias the resources, we still have to zero-fill, because otherwise the behavior would be non-portable with an implementation that did alias the resources.

  4. litherum commented on Jul 20, 2018

    @litherum
    ContributorAuthor

    Given that, the "...without notifying WebGPU program" part sounds like we're planning to handle at least some device loses in the browser without propagating it to WebGPU apps. Is it right?

    I think we covered this on the call this week. When under memory pressure, Windows will (silently?) evict arbitrary resources from the GPU (and it may/will make bad choices because it doesn't have enough information to make good choices). Metal will also evict resources when under memory pressure. So this is a situation where the context is degraded but still valid.

  5. RafaelCintron commented on Jul 24, 2018

    @RafaelCintron
    Contributor

    If there is memory pressure on Windows, the Video Memory Manager will evict resources from the GPU behind the application's back. In the past, API call frequency and other heuristics were used to determine which resources were best suited for eviction. Since D3D12 is bindless and geared towards lower level usage, these heuristics have been removed in favor of manual Evict and MakeResident calls.

    The problem with on-the-fly memory allocation is that it weakens the getObjectStatus API. Applications that wish to handle OOM for critical resources like mesh textures will be unable to do so if getObjectStatus always returns "valid". If we had a way for resources to be tagged as "purgable" at creation time then getObjectStatus would become more useful.

    I agree we should have an Unpurge or Commit API if we have Purge.

    D3D devs recommended we use D3D reserved (tileable) resources as the implementation of purgable ones. Once a resource is purged, all of its tiles can go into a memory pool to be used when you call commit or unpurge. Since tiled resources can be sparse, the tiles that make up resource C do not have to be contiguous in memory and can even belong to different heaps.

  6. litherum commented on Jul 24, 2018

    @litherum
    ContributorAuthor

    @RafaelCintron Cool! I've got two questions about that: How does an application know when it's time to start evicting things because it's running low on memory? Also, which getObjectStatus API are you referring to?

  7. dmikis commented on Jul 25, 2018

    @dmikis

    @litherum @RafaelCintron Thanks for clarifications!

    @litherum, I'm guessing that Rafael's talking about RegisterVideoMemoryBudgetChangeNotificationEvent .

  8. RafaelCintron commented on Jul 26, 2018

    @RafaelCintron
    Contributor

    The getObjectStatus API I was referring to is the one outlined in the Error Handling Explainer

    As @dmikis says, RegisterVideoMemoryBudgetChangeNotificationEvent can be used to get a notification when the budget for your application has changed. QueryVideoMemoryInfo can be used to find out what the budget is.

  9. grovesNL commented on Jul 26, 2018

    @grovesNL
    Contributor

    Regarding zero-filling, it seems like this adds a lot of overhead to resources only to ensure the developer is using the API correctly. Could we design the API to avoid this situation?

    We also discussed the concept of having a debug/validation mode previously. Would it be possible to enable zero-filling only for that mode, or try to detect/warn for these cases instead of zero-filling?

  10. kainino0x commented on Jul 26, 2018

    @kainino0x
    Contributor

    The general consensus of the group has been that portability should be maximized - that we do not want content to run differently on different devices (e.g. devices which give different results for uninitialized resources).

    In particular, if you write against the debug mode, and the debug mode zero-fills all resources, then your application could very easily break when you turn off debug mode. (But it might accidentally keep working on only some devices!)

    (IIRC) I think we would try to zero-fill only if the user would otherwise use a (partially) uninitialized resource - that is, if you upload a complete resource, then a zero-fill shouldn't need to happen. However it's certainly possible that implementations would not be able to avoid the zero-fill in every case.

  11. kainino0x commented on Jul 26, 2018

    @kainino0x
    Contributor

    One way to improve the zero-filling heuristic would be to specifically have conformance tests that ensure zero-fills are not done in certain situations. I think we could do this if we are able to issue some kind of code-visible warning about implicit zero-fills in tests.

  12. grovesNL commented on Jul 26, 2018

    @grovesNL
    Contributor

    In particular, if you write against the debug mode, and the debug mode zero-fills all resources, then your application could very easily break when you turn off debug mode.

    Right, if the application relies on implicit zero-filling. I mean debug mode could fill with a random value each time to emulate access to uninitialized memory.

  13. Kangz commented on Jul 29, 2018

    @Kangz
    Contributor

    Going back to the original proposals after the discussion we had in the calls:

    • Solution A: Theoretically this is the best solution but there are big practical issues. First it would require apps to do invasive changes to be able to make a graph before recording commands. Also the graph coloring problem reduces to finding the best allocation for a given graph, so this is NP-Complete (although a greedy algorithm might be good enough). Finally making the interference graph between resources needs to take into account resources that need to live through work that doesn't need them, which would be a large pitfall.
    • Solution B: This is similar to what Frostbite presented they do on D3D12 on PC. They say it gives them most of the gains they have on more flexible console APIs. The difference we have is that Frostbite knows exactly how much memory each resource needs, while in WebGPU we can't have the equivalent of vkGetMemoryRequirements. This would mean that WebGPU applications would have to make educated guesses at the size of resources to know which resource to alias with which.
    • Solution C: As discussed in the call, this is only marginally better than a smart / fast allocator deallocator. Purge is essentially a Destroy and Unpurge is a Create. The only benefit of it seems to be there would be less GC, and that the WebGPU implementation gets a hint that the resource might come back.

    Solution B looks like the best tradeoff because it does give the implementation very strong hints at what can be aliased and is very explicit so that applications can have a good idea of what happens under the hood.

    Zero-filling isn't that big a problem because it can be made lazily and should be skippable in most cases. (Except maybe when a render pass does a full screen opaque draw but the WebGPU implementation doesn't know it).

  14. kvark commented on Jul 30, 2018

    @kvark
    Contributor

    Solution B, as I mentioned on the call, needs to have a more complex API in order to support more than a single resource being aliased (e.g. "A | (B & C)"). And it's not obvious if the user like Frostbite can efficiently provide this information beforehand.

    Also, Solution D is missing: don't provide any extra APIs, rely on fast resource creation/freeing in the first place.

  15. Kangz commented on Jul 30, 2018

    @Kangz
    Contributor

    Solution B, as I mentioned on the call, needs to have a more complex API in order to support more than a single resource being aliased (e.g. "A | (B & C)"). And it's not obvious if the user like Frostbite can efficiently provide this information beforehand.

    Agreed, and I think each possible alias definition should be a set of resource descriptors. What makes you think a user like Frostbite might not be able to take advantage of it? Looking at the presentation it seems like a logical extension of what they are doing on D3D12 on PC.

    A possible API for solution B might be (I didn't take any time to polish the UX):

    interface WebGPUAliasHeap {
        WebGPUTexture getTexture(int setIndex, int resourceIndex /*in the set at setIndex*/);
        WebGPUBuffer getBuffer(int setIndex, int resourceIndex /*in the set at setIndex*/);
    };
    
    partial interface WebGPUCommandBuffer {
        void useAliasSet(WebGPUAliasHeap heap, int indexOfSetToUse);
    };
    
    dictionary WebGPUAliasHeapDescriptor {
        sequence<WebGPUAliasHeapResourceSetDescriptor> sets;
    }
    
    dictionary WebGPUAliasHeapResourceSetDescriptor {
        sequence<WebGPUTextureDescriptor> textures;
        sequence<WebGPUBufferDescriptor> buffers;
    };
    
    partial interface WebGPUDevice {
        WebGPUAliasHeap createAliasHeap(WebGPUAliasHeapDescriptor);
    };
    

    Agreed about Solution D, I was suggesting Solution C should be D instead.

  16. litherum commented on Aug 1, 2018

    @litherum
    ContributorAuthor

    Deferred until after MVP.

  17. added this to the post-V1 milestone on Sep 2, 2021
  18. juj commented on Oct 15, 2024

    @juj

    An application often can't simply reuse the same resource in multiple places in their frame (meaning: textures A and C usually can't literally be the same resource), because the resources may be required to be different sizes or formats.

    Could this be the abstraction that would get relaxed in a future WebGPU version? I.e. allow creating views to existing textures in a way that allows different sizes or formats? That would then seem to solve use case #2379 as well?

    This way the browser would not need to solve crazy graph coloring problems, but let the application developer choose their strategy to do so?

    (Btw, does current createView() cover the "or formats" part? It seems like it would then be only the "allows different sizes" part that is missing, which is the same as what #2379 would need)

  19. Kangz commented on Oct 15, 2024

    @Kangz
    Contributor

    createView covers part of the "or formats" but it's pretty limited at the moment. I could potentially be expanded by extension but I don't recall what made us choose the current, very restricted compatibility matrix.

    For different width / height, I believe that some APIs allow to mix and match render target of different sizes, as long as the render area is a subset of all of them. If we could do that portably, would it help your usecase? (we can't change the size in the view as that's also used for sampling and storage textures and resizing is not possible there)

  20. sunnyps commented on Mar 14, 2025

    @sunnyps

    First, some background: we're in the middle of porting rasterization in Chrome to Skia's new GPU backend, Graphite, and we're using Dawn as the graphics API middleware. We've already launched this on Macs with Apple Silicon GPUs.

    For Graphite, we have an internal Dawn extension in Chromium called transient-attachments that allows specifying a wgpu::TransientAttachment usage on textures, and in the Dawn Metal backend we make these textures memoryless (i.e. in tile memory only) if supported. The objective was to allow Skia to make its MSAA and depth-stencil be memoryless by specifying the transient attachment usage.

    I suspect we could prototype some limited resource aliasing on top of the TransientAttachment texture usage when memoryless is not supported (non-TBDR GPUs) i.e. textures with that usage will be allowed to be aliased since we don't need to preserve them between draws. Now to be clear, this doesn't solve the general problem e.g. the textures A & C example from above, but it does provide an idea - we could add a texture usage flag for aliasable/discardable textures. For these textures, we would implicitly allocate them from an alias heap and allow the client to call discard() or purge() on them (basically Solution C from above).

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions