Culling and the frame
Transient memory and aliasing
Most render targets are needed for only a few passes of the frame. If each one gets its own memory, most of that memory sits idle. Memory aliasing lets resources that are never alive at the same time use the same bytes. This page explains lifetimes, heaps, how to pack the resources, and the barrier that every takeover needs. The last part shows how RASM does it.
In short
- A transient resource lives only inside one frame, from the first pass that uses it to the last. Its lifetime is an interval of passes.
- Two resources whose lifetimes do not overlap can use the same bytes. This is aliasing. The memory needed is at least the peak: the most bytes alive in any one pass.
- The device tells you a resource's size, alignment and memory types before it exists. You allocate one big heap and create each resource at an offset in it.
- Choosing the offsets is a packing problem (NP-hard in general). The usual greedy method: biggest first, each at the lowest aligned offset that no overlapping resource uses.
- Memory that changes owner holds garbage. The new resource's first use must overwrite it, after a global barrier, because an image barrier covers only its own image. Last frame's users count too.
1The problem: memory that sits idle
A modern frame draws into many textures that nobody sees: a G-buffer, an HDR color target, bloom, a tone-mapped image, an anti-aliased image. Each one is read by the next pass or two, and then it is not needed any more. But if each one has its own memory, that memory stays reserved for the whole frame, and for every frame after it.
Full-screen textures are big. One pixel of an RGBA8 or D32 texture is 4 bytes, so at 1920 × 1080:
1920 × 1080 × 4 B = 8,294,400 B = 7.9 MiB (1 MiB = 1,048,576 B)
| Format | Bytes per pixel | 1920 × 1080 | 2560 × 1440 | 3840 × 2160 |
|---|---|---|---|---|
| RGBA8, D32 | 4 | 7.9 MiB | 14.1 MiB | 31.6 MiB |
| RGBA16F (HDR) | 8 | 15.8 MiB | 28.1 MiB | 63.3 MiB |
| RGBA8 with 4× MSAA | 16 | 31.6 MiB | 56.3 MiB | 126.6 MiB |
Real sizes are often a little bigger: the GPU stores images in tiles and pads the edges. This page uses one small post-processing frame as its example, with round sizes close to 1920 × 1080:
The fix is to let textures that are never needed at the same time use the same memory. To do that, we must know when each texture is needed.
2Lifetimes are intervals
Put the passes in the order they run and number them. A transient resource's lifetime is the interval from the first pass that uses it to the last one. Before its first pass nothing is in it yet; after its last pass nobody reads it again. A render graph knows the order and every pass's reads and writes, so it can compute every lifetime (see render graphs).
Both ends count
A pass that reads one texture and draws another uses both at the same time. So the two ends of a lifetime are inclusive.
They meet in one pass: overlap
HDR ends in pass 3 and LDR starts in pass 3. They overlap and must not share.
A gap between them: no overlap
The G-buffer is dead after pass 1. LDR is born in pass 3.
Lifetimes [a, b] and [c, d] overlap when
a ≤ d and c ≤ b
The lower bound
Add up the sizes of the resources alive in each pass. The largest sum is the peak. Any layout needs at least that much memory, because all those bytes are in use at the same moment.
3Memory requirements, heaps and placed resources
Usually a resource and its memory are made together: create the texture, and the allocator gives it memory of its own. That is a dedicated (or committed) allocation. To share memory, the two steps must be split: first get one big block of memory, a heap, then create each resource at an offset inside it. Such a resource is placed.
Dedicated
Simple: each one is created, sized and freed alone. The driver may also prefer it for render targets.
Placed
One allocation. A resource is a heap and an offset. Resources that never live together share bytes.
A placed resource does not own its memory: destroying it leaves the heap alone, and the heap must outlive every resource in it. For heaps and memory types in general, see GPU memory.
Asking before creating
To pack resources into a heap, we must know their needs before we place them. Every API can tell the needs of a resource from its description alone (size, format, usage), without creating it:
size
The bytes the resource uses. It can be more than width × height × bytes per pixel, because of tiling and padding.
alignment
The offset in the heap must be a multiple of this number, a power of two. Images often need several KiB.
memory types
A bit mask: bit i set means memory type i can hold the resource. The heap's type must be one of them.
| API | Ask, make the heap, place a resource |
|---|---|
| Vulkan | Ask with vkGetDeviceImageMemoryRequirements (Vulkan 1.3; no image needed). Make the heap with vkAllocateMemory. Create the image, then bind it at an offset with vkBindImageMemory. |
| Direct3D 12 | Ask with GetResourceAllocationInfo. Make the heap with CreateHeap. Place with CreatePlacedResource. |
| Metal | Ask with heapTextureSizeAndAlign. Make the heap with makeHeap. On a placement heap, place with makeTexture(descriptor:offset:). |
4Packing: where each resource goes
Now each resource is a rectangle. Its width is its lifetime, which is fixed. Its height is its size. We choose only its offset: how high it sits. Rectangles must not overlap, and the goal is the lowest total height, the heap size. In computer science this is dynamic storage allocation. Finding the best answer is NP-hard, so engines use a fast heuristic instead.
The common heuristic is greedy first fit, biggest first:
- Sort by size, biggest first. Big pieces are the hardest to fit. Small pieces placed later can fill the gaps between them.
- For each resource, collect the blockers. These are the resources already placed whose lifetimes overlap its own. Sort them by offset.
- Walk up from offset 0. If the resource fits below the next blocker (after rounding up to its alignment), stop. If not, jump past the end of that blocker and try again.
- Place it. It goes at that offset. The heap size is the highest end of any resource.
Here are the five textures, sorted: G-buffer 32, HDR 16, LDR 8, AA 8, Bloom 4. LDR and AA are the same size, so they keep their order. Step through it:
1. G-buffer: the biggest goes first
G-buffer: 32 MiB, passes 0 to 1. The list is sorted by size: G-buffer 32, HDR 16, LDR 8, AA 8, Bloom 4. Nothing is placed yet, so it goes at offset 0. The first one always goes at offset 0. Heap: 32 MiB.
2. HDR: blocked by the G-buffer
HDR: 16 MiB, passes 1 to 3. Pass 1 (Lighting) reads the G-buffer and draws HDR, so both are alive there. The G-buffer uses 0 to 32, and HDR must not touch those bytes. Lowest free offset: 32. The heap grows to 48 MiB.
3. LDR: takes the G-buffer's bytes
LDR: 8 MiB, passes 3 to 4. It lives together with HDR only (32 to 48). Try 0: 0 + 8 ≤ 32, it fits. Offset 0. The G-buffer is dead by then. This is the first aliasing: LDR reuses bytes 0 to 8, which the G-buffer used in passes 0 and 1.
4. AA: blocked by LDR
AA: 8 MiB, passes 4 to 5. It lives together with LDR (0 to 8). Lowest free offset: 8. AA only has to avoid LDR. HDR is dead after pass 3, and the G-buffer after pass 1.
5. Bloom: fills a gap
Bloom: 4 MiB, passes 2 to 3. Blocked by LDR (0 to 8) and HDR (32 to 48), by offset. Try 0: hits LDR. Try 8: 8 + 4 ≤ 32, fits. Offset 8. AA is there too, but in passes 4 to 5: no overlap. Done: 48 MiB instead of 68 MiB. That equals the peak from section 2, so for this frame the greedy result is the best possible.
| Step | Texture | Size | Lifetime | Blockers, by offset | Offset | Heap |
|---|---|---|---|---|---|---|
| 1 | G-buffer | 32 | 0 – 1 | none | 0 | 32 |
| 2 | HDR | 16 | 1 – 3 | G-buffer 0 – 32 | 32 | 48 |
| 3 | LDR | 8 | 3 – 4 | HDR 32 – 48 | 0 | 48 |
| 4 | AA | 8 | 4 – 5 | LDR 0 – 8 | 8 | 48 |
| 5 | Bloom | 4 | 2 – 3 | LDR 0 – 8, HDR 32 – 48 | 8 | 48 |
Sizes and offsets in MiB. The result, 48 MiB, equals the peak, so it is the best possible for this frame. That is not always so: when many resources start and end at different times, the greedy result can be above the peak. In practice it is close, and it is fast: n resources need about n² overlap tests, which is nothing for a few dozen render targets.
Try other lifetimes. The picture below runs the same greedy packing each time a lifetime changes.
struct Request
{
uint64_t size = 0;
uint64_t alignment = 1;
uint32_t first = 0; // first pass that uses it
uint32_t last = 0; // last pass that uses it, included
};
uint64_t alignUp(uint64_t value, uint64_t alignment)
{
return (value + alignment - 1) / alignment * alignment;
}
bool overlap(const Request &a, const Request &b)
{
return a.first <= b.last && b.first <= a.last;
}
// Writes each request's offset and returns the heap size.
uint64_t pack(const Request *req, uint32_t count, uint64_t *offsets)
{
std::vector<uint32_t> order(count);
std::iota(order.begin(), order.end(), 0u);
auto bigFirst = [req](uint32_t a, uint32_t b)
{ return req[a].size > req[b].size; };
std::stable_sort(order.begin(), order.end(), bigFirst);
uint64_t heapSize = 0;
std::vector<uint32_t> placed;
for (uint32_t i : order)
{
// The placed ones alive at the same time, lowest offset first.
std::vector<uint32_t> blockers;
for (uint32_t j : placed)
{
if (overlap(req[i], req[j]))
blockers.push_back(j);
}
auto lowFirst = [offsets](uint32_t a, uint32_t b)
{ return offsets[a] < offsets[b]; };
std::sort(blockers.begin(), blockers.end(), lowFirst);
// Stop at the first gap that is big enough, else jump past.
uint64_t offset = 0;
for (uint32_t j : blockers)
{
if (alignUp(offset, req[i].alignment) + req[i].size <= offsets[j])
break;
offset = std::max(offset, offsets[j] + req[j].size);
}
offsets[i] = alignUp(offset, req[i].alignment);
heapSize = std::max(heapSize, offsets[i] + req[i].size);
placed.push_back(i);
}
return heapSize;
}
Alignment
An offset must be a multiple of the resource's alignment. So the free offset found by the walk is rounded up: alignUp(x, a) = ⌈x / a⌉ · a. The bytes skipped by the rounding are lost. The heap itself must start at an address that suits every resource in it, so its alignment is the largest one.
Memory types
A heap is one allocation, so it has one memory type. A resource may go into a heap only if the resource's memory-type mask has the heap's type in it. Color and depth textures, or buffers and textures, can report different masks. So resources are split into groups, and each group gets its own heap and its own packing.
Same mask
Resources with exactly the same mask share a heap.
Simple. Can make more heaps than needed.
Shared type
Resources whose masks have a common bit share a heap of that type.
Fewer heaps, more sharing. A little more code.
On most desktop GPUs, all render targets accept the same device-local memory, so one heap is the usual result.
5Taking over memory
When a resource starts to use bytes that another resource used before, three rules apply.
1. The contents are garbage
The bytes still hold the old resource's data, which means nothing to the new one. So the new resource's first use must write all of it. A transient resource must never be read first.
First use reads
The new resource shows what the old owner left in the bytes.
First use writes everything
A clear, or a "discard" followed by a pass that writes every pixel.
GPUs keep hidden compression data next to many render targets, and that data is wrong too. In Vulkan, the first use also starts from the UNDEFINED layout, which tells the driver to throw the old contents away, compression data included.
2. A barrier between the old owner and the new one
The GPU runs passes in parallel unless a barrier tells it to wait (see GPU synchronization). Without a barrier, the new resource's writes can land while a pass still reads the old resource, or the old resource's writes, still in a cache, can reach memory after the new ones:
The natural barrier is the one that moves Y into its first layout. But an image barrier only covers its own image: its memory part flushes and waits for writes to Y, not to X. So aliasing needs a barrier that covers all memory:
| API | The barrier for a takeover |
|---|---|
| Vulkan | A global memory barrier (VkMemoryBarrier2): wait for the stages that used the old resources, flush their writes, before the stages of the new one. Then the image barrier from UNDEFINED as usual. |
| Direct3D 12 | An aliasing barrier, D3D12_RESOURCE_BARRIER_TYPE_ALIASING, naming the resource before and the resource after (or none, meaning "any"). |
| Metal | Resources from a heap are usually not tracked. A MTLFence, updated after the old resource's last pass and waited for before the new one's first pass. |
3. Last frame counts too
The layout is the same every frame. So the first owner of some bytes in frame N+1 takes them over from their last owner in frame N. A new frame is not a barrier: commands from two submissions on one queue may overlap on the GPU.
6Variants
When to pack
Once, when the graph changes, or every frame.
Once is cheap and keeps heaps stable. Every frame fits graphs that change each frame (a pass on or off), but needs a pool of heaps to take memory from.
What aliases
Render targets only, or buffers too.
Buffers pack the same way. In Vulkan, a buffer and an image next to each other in one heap must keep the device's bufferImageGranularity apart.
Frames in flight
One layout for all frames, or one heap per frame slot.
One layout uses the least memory and needs the cross-frame barrier. One heap per slot avoids that hazard, for twice the memory.
Heap per
Graph, or whole engine.
One heap per graph is simple. One shared pool lets two graphs, or two views, reuse each other's memory.
Direct3D 12
CreateHeap, then CreatePlacedResource at an offset. On resource heap tier 1 hardware, a heap holds only one kind of resource: buffers, render-target and depth textures, or other textures. Tier 2 allows a mix. The first use of an aliased render target must be a clear, a DiscardResource or a full copy.
Metal
A MTLHeap of the automatic type places resources itself: makeAliasable on a resource lets later resources from the heap take its memory. A placement heap takes explicit offsets, as on this page. Either way, fences order the takeover.
No memory at all: memoryless attachments
Tile-based GPUs (most phones, and Apple GPUs) draw a render pass one small tile at a time, in on-chip memory. An attachment that is cleared at the start of the pass and not stored at the end, like a depth buffer used only inside one pass, never needs to reach main memory. It can be memoryless. That is aliasing taken to the end: zero bytes.
Metal
MTLStorageMode.memoryless.
Vulkan
A lazily allocated memory type (VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) with a transient attachment.
It depends on the pass's load and store ops; see load and store ops. Desktop GPUs usually have no such memory type.
7Pitfalls
- Reading before the first write
- The first use reads the previous owner's data. Nothing fails; the image just shows garbage, often only on some GPUs. A graph should reject a transient whose first use is a read.
- Forgetting the last frame
- The barrier at a resource's first use must also cover the previous frame's last users of the same bytes. A barrier that only looks at earlier passes of the same frame misses them.
- An undeclared use
- A pass that samples a texture without declaring it is outside the lifetime. By then another resource may own the bytes. Every read and write must be declared.
- Keeping a handle after the last pass
- A texture handle or descriptor still points at the old bytes, but a different resource writes them now. Reading it shows that resource's data, with no error.
- Resize
- New sizes mean a new layout and new heaps. The GPU must be done with the old heaps before they are freed. For a moment, both may exist.
- Debugging
- Capture tools show an aliased texture's bytes even outside its lifetime, so it seems to hold another texture's image. That is expected.
- Fragmentation
- Alignment gaps and greedy choices can leave a heap above the peak. Compare the heap size with the peak to see how much.
8In RASM
RASM aliases the render targets of a render graph. A render target that RenderGraph::createRenderTarget or PassBuilder::createRenderTarget makes without history or readable is transient: its handle exists at once, but its textures are made only after the graph is compiled, inside heaps shared with the graph's other transient targets. The packing is the greedy method of section 4, in rhi::packAliased.
examples/01_render_graph has two transient targets. offscreen_rt (one color and depth) lives in passes 3 to 8: Scene 1 draws it, Hi-Z reads its depth, Scene 2 and Transparent draw it again, and Trail reads it. composite_rt (two colors and depth) lives in passes 9 and 10. Their lifetimes do not overlap, so they share one heap. trail_rt has history, so it has memory of its own.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| What is transient | any resource made inside the frame | Render targets without history or readable from RenderGraph::createRenderTarget or PassBuilder::createRenderTarget. Textures and buffers from the builder, history targets, readable targets (a readback copies them after the frame's last pass, readbacks), and targets from Renderer::createRenderTarget get their own memory. |
| Lifetime | first to last use, both ends included | The same, as positions in the sorted order (RenderGraph::transientLifetimes). A target that no pass declares lives the whole frame. |
| Looking inside | – | A transient target holds its data only during its lifetime. The RASM window's Buffers section copies one with an Inspect pass placed right after its last writer, which counts as a use, so its lifetime covers the copy (Inspecting GPU resources). Adding or removing that pass lays the memory out again. |
| One request per | resource | Texture: each color and the depth of a target is its own request, with the target's lifetime (attachmentTextureDescs). |
| Asking | needs from the description | VulkanDevice::getTextureMemoryRequirements, with vkGetDeviceImageMemoryRequirements. |
| Packing | greedy, biggest first, lowest free aligned offset | The same (rhi::packAliased). Equal sizes keep their order (a stable sort). |
| Memory types | same mask, or a shared type | Same mask: one heap per exact memoryTypeBits value. |
| Heap | one allocation | VulkanDevice::createHeap: one dedicated VMA allocation (vmaAllocateMemory), device-local preferred, with the largest alignment. Textures are placed with vmaCreateAliasingImage2. |
| When | once, or every frame | Once per compile that changes the lifetimes. A resize places a layout again if one of its targets is sized from the window (RenderTargetDesc::swapchainScale), or when Renderer::resizeRenderTarget gives one of its targets a new size; the textures keep their handles. |
| First use | a full write | The first pass on a target draws it and clears it (RenderGraph::assignAttachmentOps). compile fails if a pass reads a transient target first: Pass '...' reads a transient render target that no pass before it draws. |
| Barrier | global, before the first use | RenderContext::aliasingBarrier: one VkMemoryBarrier2 before each pass where a transient target starts, one per pass even if two start there. |
| Last frame | covered by the same barrier | Yes: on one queue, a barrier's first half covers earlier submissions. With async compute, the graph also makes a target's first pass wait for the other queue's last pass this frame that used a transient target (Renderer::waitForQueue); the frame before ends with graphics waiting for all compute work. One layout for both frame slots. |
| Graphs | one heap per graph, or a shared pool | One per graph: each graph's targets are one TransientGroup with its own heaps. |
| Bindless slots | – | A new layout's textures take the old textures' slots (RenderContext::createAttachments), so placing again does not use up the bindless set. |
| Failure | – | If a heap or texture can't be made, the frames draw no passes and the graph tries again every frame (RenderGraph::placeTransients). |
| Buffers, memoryless | variants | No: only render targets alias, and nothing is memoryless. |
The barrier
VulkanCommandBuffer::aliasingBarrier records this one memory barrier. It waits for every attachment and storage write, and for fragment and compute shader work (the reads of the old owner), before the new owner's attachment or compute work:
| Field | Value |
|---|---|
srcStageMask | VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BITVK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHRVK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHRVK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BITVK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT |
srcAccessMask | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BITVK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BITVK_ACCESS_2_SHADER_STORAGE_WRITE_BIT |
dstStageMask | the three attachment stages (the first three above) and VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT |
dstAccessMask | color and depth attachment reads and writes, shader storage reads and writes |
Then beginPass moves the target's attachments from UNKNOWN, which is an image barrier from the UNDEFINED layout, and clears them. A storage target's first pass is a compute pass instead, which moves its colors to STORAGE and writes every texel.
Lifetime of the memory
The graph owns its transient targets. RenderGraph::~RenderGraph calls RenderContext::destroyRenderTargets, which waits for the GPU, destroys the textures, and frees a group's heaps once none of its targets is left. A RenderGraph is move-only, so two graphs never free the same targets. Placing a layout again first waits for the GPU to be idle, then builds the new heaps and textures, then frees the old heaps.
Where it lives in code
| What | Where |
|---|---|
| Packing | rhi::packAliased, rhi::AliasRequest, rhi::AliasPlacement, rhi::AliasHeap in src/rhi/memoryAliasing.h and src/rhi/memoryAliasing.cpp |
| Lifetimes, placing, barrier | RenderGraph::transientLifetimes, RenderGraph::compile, RenderGraph::placeTransients, RenderGraph::execute in src/renderer/renderGraph.cpp |
| Transient targets | RenderContext::createTransientRenderTarget, RenderContext::placeTransientRenderTargets, RenderContext::placeGroup, RenderContext::createAttachments, RenderContext::destroyRenderTargets, RenderContext::resizeRenderTargets in src/rhi/renderContext.cpp |
| Device side | VulkanDevice::getTextureMemoryRequirements, VulkanDevice::createHeap, VulkanDevice::createPlacedTexture in src/rhi/vulkan/vulkanDevice.cpp; the interface in src/rhi/device.h |
| The barrier | RenderContext::aliasingBarrier; VulkanCommandBuffer::aliasingBarrier in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Tests | tests/memoryAliasingTests.cpp (sharing, inclusive ends, gaps, alignment, memory types, no shared byte); tests/renderGraphTests.cpp (lifetimes) |
| Example | examples/01_render_graph/main.cpp |
- A transient target's first pass draws it. Declare every read with
PassBuilder::read, so the lifetime covers it. A texture or bindless index used outside the declared passes reads another target's bytes, with no error. - Lifetimes are inclusive at both ends. A pass that reads one target and draws another uses both.
- If transient targets get a new kind of use (copies, a new shader stage), add its stages and accesses to
VulkanCommandBuffer::aliasingBarrier. Today it covers attachment writes, compute storage writes (storage targets, such as bloom's levels) and fragment and compute reads. - Placed textures do not own their memory. Destroy them before their heap (
destroyHeap), and wait for the GPU before a heap is freed. - A change to
rhi::packAliasedcomes with a test intests/memoryAliasingTests.cpp, and the test that no two overlapping lifetimes share a byte must still pass.
Transient textures and buffers: only render targets are transient (D9 in docs/code_review.md). There is also no heap pool that two graphs share. The API of the functions above is in the low-level API and the render graph API.
Further reading
- Yuriy O'Donnell, FrameGraph: Extensible Rendering Architecture in Frostbite, GDC 2017: transient resources and aliasing in a frame graph.
- Michael R. Garey and David S. Johnson, Computers and Intractability (1979): "dynamic storage allocation" is NP-complete.
- The Vulkan specification, section Memory Aliasing in the chapter Resource Creation.
- Microsoft, Direct3D 12: Memory aliasing and data inheritance, and Using resource barriers (aliasing barriers).
- Apple, the Metal documentation on heaps: MTLHeap and makeAliasable().
- Related guides: render graphs, GPU memory, GPU synchronization, load and store ops, history buffers.