Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

GPU Memory Aliasing

12 min readJul 10, 2020

--

Modern graphic APIs such as DirectX 12 or Vulkan expose an ability to place allocated GPU resources into user-defined memory locations in manually created heaps. It allows us to create textures and buffers, memory of which overlaps partially or even completely.

When is that useful?

Rendering engines are often referred to as pipelines for a reason. They are usually organized as a conveyor with multiple stages of rendering work, where each stage consumes and produces GPU resources.

Take a typical frame in a game engine: rasterize some geometry, perform shading, maybe compute some volumetrics, then run a bunch of post-processing stages. Each stage here will produce its output by writing into textures and/or buffers that will be read by some other stage later in a frame.

The observation here is that resources produced by a certain stage may be only used by a handful of other stages. Post processing render passes are a good example: bloom pass can produce its output that will be consumed only by the next stage — tone mapping and not be needed anywhere else in the frame. We can see that a resource can have a small effective lifetime, but most likely is allocated beforehand and occupies its memory throughout the whole frame. A large pipeline can have a lot of produced resources that will all sit in their permanently occupied memory regions and consume a lot of VRAM. Unless we do something about it.

At first, we might think that if resource is used in a short time frame, we might allocate it on the spot when it’s used first and deallocate when it’s not needed instead of allocating beforehand, to reduce overall VRAM consumption. It will help memory-wise, sure, but performance hit associated with frequent memory reallocations will outweigh any potential benefits, so this is not a viable solution.

A common way to address this issue is to use pools of resources with compatible properties: pull out a non-used resource when needed and put it back when work is done to be potentially used by someone else and skip an allocation by doing so. This works well for post processing stages, for example, because they are usually implemented as full-screen render passes that all read and write to textures with identical properties. We can basically have only two textures allocated for the whole post-processing pipeline. In the essence this is a high level memory aliasing. But high level aliasing is not very flexible, it might fit well in post-processing, but is less useful in other parts of an engine, because we have to think about various incompatible resources that cannot be put in the same pool, which makes memory reuse not as efficient as it could be.

This is where low-level aliasing enabled through graphic APIs themselves starts to make sense. When we use API to alias memory we stop caring about resource types and worry only about their sizes and memory addresses. We can still allocate resources once, beforehand, to avoid performance hit, but we can also pack them in memory more efficiently than in pool example, by placing resources used in disjoint periods of time “on top” of each other in the same memory region disregarding resource type, because at the low level they are just a bunch of bytes in VRAM.

Algorithm

So we established that aliasing can be useful, but how can we actually implement it to pack memory efficiently?

Let’s not burden ourselves at the beginning too much and consider a render pipeline with work executed serially one after another and do not think about asynchronous work execution or anything like that yet.

Take a random example of serially executed render passes that read resources of various sizes.

Press enter or click to view image in full size
Arbitrary render pipeline

First thing we need to do is determine effective lifetime (EL) of each resource, because we can only alias them if they’re disjoint in time, otherwise we would encounter memory corruption. Since render passes are executed serially we can assign an execution index to each of them and use those indices for lifetime construction.

For each resource we take index of a first render pass the resource is used in and treat it as a start of a EL range, index of last pass resource is used in becomes an end of the range.

This is what we get after assigning a EL to each resource:

Press enter or click to view image in full size
Resource effective lifetimes

Now back to memory packing. We want to have as little memory footprint as possible, but how low can we possibly go? If we look at example resources we see that the largest one is D with size of 15 megabytes, so even if we’d place every resource on top of each other disregarding lifetimes we’d use 15 MB of memory, which means that in the best case scenario a total amount of memory will be at least the amount required by the largest resource.

That gives us a hint that a good way to overlap memory is to start from the largest resource and then try to pack smaller ones in that memory region like a nesting doll.

That leads us to next step of the algorithm: sort resources in descending order of their size.

Press enter or click to view image in full size
Sorted resources

Now let’s walk through this ordered list and actually try to tightly arrange memory of resources that do not have EL conflicts.

We take first resource in the list, which is also largest (D), and place it in a new memory bucket.

Press enter or click to view image in full size
Memory bucket created from the largest resource 15 MB in size

First resource is always accepted into a bucket because it is simply first, but subsequent resources are trickier.

Take second resource (A) and see if we can put it in the same bucket with (D) by checking for EL conflicts.

Press enter or click to view image in full size
Effective lifetimes of A and D do not overlap

Since lifetimes do not conflict with each other (i.e. do not overlap) we put (A) into the same bucket.

But wait a minute, (A) is only 10 MB in size so it can be put at many various addresses inside of 15 MB bucket. Where should we actually place it? Address 0 seems like a natural choice, so let’s just put (A) there.

Press enter or click to view image in full size
A and D aliased in the same memory bucket

Next resource is (J), but now we have two aliased resources in a bucket, so how should we proceed? We now must take (J) and see how its EL fits ELs of resources already in the bucket.

Press enter or click to view image in full size
J and D lifetimes in conflict with each other

We see that even though (J) does not have a lifetime conflict with (A), it conflicts with (D) and unfortunately, there no place in this bucket where (J) could be placed to not overlap with (D) memory-wise, so we skip adding (J) to the bucket.

We then take (K), but it has the same problem of conflicting with (D), so it’s also skipped.

Next one is (E) and it is a bit more interesting.

Press enter or click to view image in full size
E conflicts with A

Now we have a different conflict between (A) and (E) and it is different because (A) does not occupy the bucket completely, only 2/3 of it, which means we have 5 MB of memory left. We should try to put (E) at 10 MB offset then (where (A) ends), but since E’s size is 8 MB there is just not enough available space left in the bucket and therefore (E) must also be skipped.

You might’ve guessed where we’re going with this, but let’s get to the end of the list.

(I), (L), (B), (H) are skipped due to conflict with (D).

Next is (F) that doesn’t conflict with (D) but conflicts with (A), but also its size is small enough (3 MB) to fit into the bucket after (A). In case of (F) the only memory region we could place it is a range between 10 and 15 MB, which is where we’ll put it.

Press enter or click to view image in full size
F conflicts with A but can still fit in the bucket

Next is (M) conflicting with (D), so it’s skipped.

Then we have (G) and with it we can see an ambiguity. Because out of all aliased resources (G) conflicts only with (F) and has a small enough size (2 MB), it is able to fit in more than one memory region.

Press enter or click to view image in full size
Multiple memory regions G can be put in

(G) fits in both 0–10 and 13–15 ranges, so which one is better? We should pick a smaller region because if we’d put (G) in the larger one, we could reduce potential number of resources that could’ve still been aliased in this bucket.

Last resource is (C) and it’s skipped due to conflicts with pretty much everything in the frame.

Get Pavlo Muratov’s stories in your inbox

Join Medium for free to get updates from this writer.

So, we ended up aliasing four resources: D, A, F and G. Not much, but definitely better than nothing. What do we do with the rest that was skipped? We create a new bucket using largest resource from what’s left and repeat the algorithm. Repeat until all resources are dispatched to memory buckets.

Press enter or click to view image in full size
All resources aliased

After aliasing all resources from above example we can see that total required memory is 52 MB versus 82 MB if no aliasing was done, so we have a ~37% reduction. This is of course an abstract example and each real render pipeline will achieve different amounts of compression.

So, by now we developed an intuition for placing resources into buckets. It’s time we generalize and formalize this process.

In general, when we try to add a resource to a bucket we need to find such memory regions that if we’d place new resource in any of them, it would not have effective lifetime conflicts with any of resources already present in the bucket.

We find such free regions by first gathering all regions that are in conflict with the new resource by iterating through all already aliased resources in a bucket and checking whether lifetimes intersect. If they do, a memory region becomes unaliasable.

Press enter or click to view image in full size
An abstract example of resources that a new resource has lifetime conflicts with, leaving only a few aliasable memory regions new resource can be placed in.

Let’s look at another abstract example, this time of unaliasable memory regions. We can tell where free regions are located, but what actually gives them away, what’s the pattern?

To locate free regions we should treat non-aliasable memory offsets as a sequence of points of two types: start point and end point.

Gather offsets from example above, assign start/end markers, sort in ascending order, then insert bucket start address with “end” marker at the beginning of the list and bucket end address with “start” marker at the end of the list (sorting is required because resources are not necessarily listed in order they reside in memory).

Press enter or click to view image in full size
Ordered and marked memory region offsets

We can now define a free region. It is located between two neighboring End and Start points, such as 0–2 or 10–11. But, there is a catch: not all End-Start pairs represent free memory patches due to overlapping such as in 6–7 example, because 6–7 pair is overlapped by a resource in range 5–8.

So a complete definition goes as follows:

A free aliasable memory region is a space between two neighboring End-Start offsets that is not overlapped by any Start-End pair.

Now how do we detect an overlap? We introduce an overlap counter, that we increase when Start point is encountered and decrease when End point is encountered. That way when we’ll reach an End-Start pair that may indicate an aliasable memory region we’ll check the counter value, and if it is zero, then there is no overlap.

Press enter or click to view image in full size
Overlap counter helps detect free aliasable regions: 0–2, 10–11, 14–15, 18–20

Now the last step is to pick the smallest suitable free region and place new resource in it.

Let’s summarize.

To alias resources, order them in descending order of their size. Take first and largest resource and place it in a new memory bucket of the same size. Iterate through the rest of the list and for each resource build an ordered list of unaliasable memory regions by checking for effective lifetime conflicts. By going through unaliasable memory list determine smallest free aliasable memory region that can fit the resource. If it doesn’t exist, skip adding resource to the bucket.

If all resources couldn’t be fit into a single bucket, remove aliased resources from original list and repeat the algorithm until all resources are aliased into N buckets, where N ≤ TotalResourceCount.

Complexity

This algorithm packs memory pretty tightly, but it is greedy. We should examine its time complexity to understand its applicability to real-world render pipelines.

We have N resources that are iterated in a loop (an outer loop). In each outer loop iteration we might have a linear search through a list of already aliased resources to find unaliasable region offsets, then a sort and then another linear search to find optimal free region.

What’s the worst case of inner loop time-wise? It is actually the best case memory-wise when all resources are placed inside of single memory bucket. What’s the maximum amount of resources we can operate on in inner loop? It’s i — the current outer loop iteration index, because we cannot have more resources to process in inner loops then we already processed in the outer one.

So if we’d only consider iterating resources in outer loop and searching for unaliasable regions in inner loop we’d get a following worst case complexity:

Search complexity

because for each iterated resource i we can only have a maximum of i-1 resources already present in the bucket, so we’d have a total complexity that looks like a series: 1 + 2 + 3 + 4 + 5 + … + N.

We now add offset sorting. Assume that we use some log-time sorting algorithm. Complexity formula grows a bit:

Search and sort complexity

Add free region search and formula becomes:

Constant work, search, sort and another search complexity

Since the amount of offsets are double the number of already aliased resources we add 2i. Then we add 2 to account for bucket start and end offsets.

We should also add initial resource sort in here as well as a constant work performed on each outer loop iteration:

Press enter or click to view image in full size
Total complexity

We can now estimate an asymptotic complexity by throwing out everything except the part that grows fastest with increasing N.

Press enter or click to view image in full size
Asymptotic complexity

This is a bit worse than quadratic complexity, but not too much.

So can we use it in a production renderer?

The answer is yes if we think about input data sizes. How many GPU resources does a modern render pipeline really allocate? Dozens, hundreds? Even if it’s a hundred or two, combining that with a fact that resource allocation (and therefore aliasing) happens rarely at initialization stage or when resource property change is requested by user and that on average it will be much quicker due to inability to place all resources in the same bucket, we can conclude that it is totally feasible.

Parallel work execution

There is one thing we left out for later: execution of render work on concurrent queues exposed by graphic APIs.

We can have a situation when resource can be read by more then one concurrently executed render passes. How do we correctly assign effective lifetime range for a resource considering that parallel jobs have different execution indices and we can’t know which one will finish last?

Press enter or click to view image in full size
Cross-queue resource reads

To solve this problem we should assign lifetime ranges with lower granularity: instead of using render pass execution indices use pass dependency level indices instead. See Organizing GPU Work with Directed Acyclic Graphs.

Code

For full implementation see PathFinder.

Excerpt from full implementation

--

--