Repository navigation
Description
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:
- 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.
- 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).
- 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
dmikis commentedon Jul 18, 2018
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?
thomasdenney commentedon Jul 19, 2018
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:
litherum commentedon Jul 20, 2018
Another detail I should have mentioned is that all three approaches require zero-filling resources aggressively. This is for two reasons:
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.
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.
litherum commentedon Jul 20, 2018
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.
RafaelCintron commentedon Jul 24, 2018
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
EvictandMakeResidentcalls.The problem with on-the-fly memory allocation is that it weakens the
getObjectStatusAPI. Applications that wish to handle OOM for critical resources like mesh textures will be unable to do so ifgetObjectStatusalways returns "valid". If we had a way for resources to be tagged as "purgable" at creation time thengetObjectStatuswould become more useful.I agree we should have an
UnpurgeorCommitAPI if we havePurge.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
commitorunpurge. 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.litherum commentedon Jul 24, 2018
@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
getObjectStatusAPI are you referring to?dmikis commentedon Jul 25, 2018
@litherum @RafaelCintron Thanks for clarifications!
@litherum, I'm guessing that Rafael's talking about
RegisterVideoMemoryBudgetChangeNotificationEvent.RafaelCintron commentedon Jul 26, 2018
The
getObjectStatusAPI I was referring to is the one outlined in the Error Handling ExplainerAs @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.
grovesNL commentedon Jul 26, 2018
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?
kainino0x commentedon Jul 26, 2018
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.
kainino0x commentedon Jul 26, 2018
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.
grovesNL commentedon Jul 26, 2018
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.
Kangz commentedon Jul 29, 2018
Going back to the original proposals after the discussion we had in the calls:
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.Purgeis essentially aDestroyandUnpurgeis aCreate. 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).
kvark commentedon Jul 30, 2018
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.
Kangz commentedon Jul 30, 2018
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):
Agreed about Solution D, I was suggesting Solution C should be D instead.
litherum commentedon Aug 1, 2018
Deferred until after MVP.
create setTimeout helper and add lint (gpuweb#63)
juj commentedon Oct 15, 2024
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)
Kangz commentedon Oct 15, 2024
createViewcovers 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)
sunnyps commentedon Mar 14, 2025
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-attachmentsthat allows specifying awgpu::TransientAttachmentusage 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()orpurge()on them (basically Solution C from above).