GPU data
GPU memory and uploads
A GPU reads its data fastest from its own memory, but the data starts on the CPU. This page explains the kinds of GPU memory, how the CPU writes into them, and the usual ways to move data across: mapped writes, staging copies, ring buffers and per-frame copies. The last part shows how RASM does it.
In short
- A discrete GPU has its own fast memory (VRAM). The CPU reaches it only across the PCIe bus, if at all.
- The API lists memory types with flags: device-local (fast for the GPU), host-visible (the CPU can map it), coherent, cached.
- Memory the CPU cannot map is filled with a staging copy: the CPU writes a host-visible buffer, and the GPU copies it over.
- A ring buffer reuses one staging buffer forever. A fence tells when the GPU has finished reading each part.
- Many small copies go out in one batch. Barriers order them against the frames that read the data.
- Data the GPU reads every frame and the CPU changes every frame needs one copy per frame in flight.
- Engines sub-allocate: a few big memory blocks, with many buffers inside each.
1Two memories, one bus
A discrete GPU is a card with its own memory chips, called VRAM. VRAM is very fast for the GPU. The CPU's memory (system RAM) is on the other side of the PCIe bus, which is much slower. An integrated GPU (most laptops, phones, Apple silicon) has no VRAM: CPU and GPU share the same RAM.
2Heaps and memory types
Vulkan (and Direct3D 12 and Metal, with other names) describe the memory as heaps and memory types. A heap is a pool of physical memory with a size. A memory type is a way to use a heap, described by flags. Every allocation picks one memory type. The four flags:
device-local
Fast for the GPU. On a discrete GPU this is VRAM.
host-visible
The CPU can map it: get a normal pointer and write or read with memcpy.
host-coherent
CPU writes become visible to the GPU without an extra call (and the other way round).
host-cached
CPU reads go through the CPU cache, so reading is fast. Without it, reads are very slow.
A typical discrete GPU on a desktop PC shows something like this:
Write-combined memory
Host-visible memory that is not cached is usually write-combined: the CPU collects writes in a small buffer and sends them over the bus in big pieces.
Write once, in order
Writing it in order, once, with memcpy, is fast.
Read, or write here and there
Reading it, or writing scattered bytes, or doing x += 1 on it, is very slow, because each read crosses the bus.
So treat mapped upload memory as write-only.
Coherent or not
Coherent
After the CPU writes, the bytes are visible to the GPU at the next submit. Nothing else is needed.
Not coherent
After writing, the CPU must flush the range (vkFlushMappedMemoryRanges). Before reading what the GPU wrote, it must invalidate the range. Ranges are rounded to nonCoherentAtomSize, a device limit of up to 256 bytes.
New memory is cleared first
The OS never gives a program bytes another program left behind. So new video memory is cleared before the program can use it. On Windows the video memory manager does this. The clear runs by itself, and the device's next submit waits until it is done.
- A submit right after a big allocation completes late. The time shows up as a long fence wait, often in the first frames.
- Host-visible video memory is cleared about 8 times slower here than device-local-only memory.
- Many small buffers come out of a few big blocks. A new block is cleared like a big buffer.
Put a big buffer the CPU does not map in device-local-only memory, and make it at startup, not while frames run.
3Two ways to fill a buffer
There are two ways to get bytes from the CPU into a buffer that the GPU reads.
| Data | Size | Changes | Usual path |
|---|---|---|---|
| Per-frame constants (camera, lights) | bytes to KB | every frame | A, into host-visible memory, one copy per frame in flight |
| Meshes, static tables | MB to GB | once, at load | B, into device-local memory |
| Textures | MB to GB | once | B (images need a copy into their tiled layout, see section 8) |
| Big tables with a few changed rows | MB | a few rows per frame | B with only the changed rows, or A with ReBAR |
4The staging ring
Making a new staging buffer for every upload is slow, and freeing it needs to wait for the GPU copy. Instead, engines keep one big staging buffer and use it as a ring. Two counters describe it: head, where the next write goes, and tail, the oldest byte the GPU may still read. Bytes between them are in use. A fence (or a timeline value) per submitted batch tells when its bytes are free again.
This example uses a 64 MiB ring. A piece is never split across the end of the ring; a piece that does not fit before the end skips to the start. Click through it.
1. An empty ring
Counters that never wrap make the math simple: head − tail is the space in use, and head mod size is the next position.
2. Upload 40 MiB
Nothing has reached the GPU yet. The copy command waits in a list until the next submit.
3. Submit: the batch goes to the GPU
The CPU does not wait. It goes on recording the next frame.
4. Next frame: space comes back, a piece skips to the start
Checking a fence value does not block. The ring only learns about finished batches; it never waits for them here.
5. If the GPU is late: the ring is full
This wait stalls the CPU. It only happens when more than a ring's worth of data is uploaded before the GPU catches up, for example a big level loaded in one frame.
Now run the ring yourself. It starts at step 3: 40 MiB are submitted as batch 1, and the GPU has not finished them.
The ring size is a trade-off. Bigger means fewer stalls but more memory that sits idle most of the time. As a rough number, a 64 MiB ring can move a lot per frame before the bus itself becomes the limit:
5Batching and ordering the copies
A copy command is cheap, but a submit is not. So uploads are collected and sent as one batch: one command buffer with many copies, submitted once per frame, before the frame's own work.
Merging
Two copies whose source and destination ranges both continue each other become one bigger copy.
Overlapping writes
Copies in one batch have no barrier between them, so their order is not defined. Two writes to the same bytes in one batch must go into two batches (or the second must replace the first on the CPU).
A transfer queue
Many GPUs have a separate copy queue that runs next to the graphics queue. Copies there do not slow the frame, but they need a semaphore to order them, and buffers may need a queue ownership transfer. See GPU synchronization.
Destroying a buffer with pending copies
Drop its pending copies, and wait for submitted batches that write it. Otherwise the GPU copies into freed memory.
6Sub-allocation
Asking the driver for memory (vkAllocateMemory) is slow, and the number of live allocations is limited: the Vulkan spec only promises 4096 (maxMemoryAllocationCount). A scene can have far more buffers than that. So engines allocate a few big blocks and place many buffers inside each one: sub-allocation.
Four kinds of allocator share out a block:
Linear (bump)
One pointer that only moves forward. Free all at once by resetting it.
Good for: data that lives exactly one frame, or forever (load once, never free).
Ring
A linear allocator that wraps around, freed in the order it was used (section 4).
Good for: staging, per-frame constants.
Free list (or TLSF)
Keeps a list of free ranges; finds one big enough; merges neighbours on free.
Good for: general buffers and textures of mixed sizes and lifetimes.
Pool
Many slots of one fixed size.
Good for: many objects of the same size.
Most Vulkan engines do not write this themselves. The Vulkan Memory Allocator (VMA) library from AMD picks memory types from usage hints, manages blocks with a free-list allocator, and handles alignment, dedicated allocations and memory budgets. Direct3D 12 has the same idea in D3D12MA.
7Changing data the GPU is reading
The CPU is usually a frame ahead of the GPU (see Frames in flight). If the CPU writes a buffer while the GPU still reads it for the previous frame, the GPU can see half old and half new data.
A direct mapped write
It is not ordered at all: the bytes change under the frame that reads them.
A staging copy
It is safe: its barrier waits for the frame that still reads.
For data that is written directly, the usual answer is one buffer per frame in flight:
Per-frame copies
Simple and fast. Costs N times the memory. Every change must be sent N times, once to each copy.
Write only new ranges
For data that only grows (a mesh pool), write each new range once, in a part no frame has read yet. One copy is enough.
8Textures
A texture is not stored row by row in GPU memory. The GPU uses an optimal tiling: a hidden, vendor-specific order (blocks, swizzles) that makes nearby texels close in memory. The CPU cannot write that order itself.
So textures need either a copy command or a special CPU path:
Mip levels add about a third. Formats with block compression (BC7, ASTC) are usually made offline. See Mipmaps and texture sampling.
9Reading data back
Sometimes the CPU needs a result the GPU computed: a count, a picked object, a timing. Reading back has its own steps, in this order:
- Use host-cached memory. Reading write-combined memory is very slow (section 2). Ask for host-visible and host-cached.
- On the GPU: a barrier to the host. After the shader or copy that writes the data, a barrier with the host as the destination stage makes the writes available to the CPU.
- On the CPU: wait for the fence. Wait for the fence of that submit. Until then the data may not be there yet.
- Invalidate, then copy. If the memory is not coherent, invalidate the range first. Then copy the bytes out.
Waiting for this frame's fence would stall the CPU until the GPU catches up. So engines read results a frame or two late: in frame N they read what frame N − 2 wrote, after the fence they already wait for anyway.
10In RASM
RASM uses VMA for all memory. A buffer is one of three kinds, set by two flags in BufferDesc. RenderContext::fillBuffer then picks path A or B of section 3 by itself: a mapped buffer gets a memcpy, any other buffer goes through the staging ring in UploadManager.
Buffer::mapped says which case you got: it is true when VMA returned a mapped pointer. hostReadable replaces the other flags, so it wins over hostVisible.fillBuffer must be correct on both.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Picking memory types | ask for flags, never hard-code types | VMA with VMA_MEMORY_USAGE_AUTO and host-access flags (VulkanDevice::createBuffer). The allocator is made with the memory-budget and device-address flags. |
| New memory is cleared | big buffers the CPU does not map in device-local-only memory, made at startup | The pools the CPU fills once are BufferDesc::staged: the geometry pools and the animation pool. On a discrete GPU they ask for no host access. Before (P35) they were in resizable-BAR memory: about 280 MiB made the first frame's fence wait up to 50 ms on an RTX 3060, and now about 1 ms. They are made when the renderer starts, except the point pool, which comes with the first point cloud. Other buffers stay mappable where all of video memory is host-visible, so the scene tables are written at once each frame; they come out of host-visible VMA blocks, and a new block is cleared too. |
| Sub-allocation | a few blocks, many buffers | VMA does it for buffers and sampled textures, which ask for no host access. Attachments and storage textures each get a dedicated allocation (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT), except transient render targets: the render graph places them in shared heaps, and two that are never used at the same time share bytes (Transient memory and aliasing). |
| Staging ring | one buffer, head/tail, a fence per batch | The same, in UploadManager: RING_SIZE = 64 MiB, chunks of at most MAX_CHUNK_SIZE = 16 MiB, counters that never wrap, one timeline fence. The stepper in section 4 is RASM's real behaviour. A ring is a BufferUsage::TRANSFER buffer: system memory, or video memory where all of it is host-visible (resizable BAR), never a small BAR heap (P10). With a transfer queue a second ring serves the loads. |
| Batches | one per frame, before the frame | Two command buffers take turns (batches). RenderContext::submit calls flush before every submit. flush also runs when the ring is full, and when a write overlaps bytes the batch already writes to the same buffer. |
| Merging | neighbouring copies become one | The same (addCopy). |
| Ordering | two barriers, or a transfer queue and a semaphore | Two global barriers in VulkanCommandBuffer::copyBuffers, on the graphics queue. With async compute, the compute queue is outside those barriers: the upload submit waits for the last compute submit, and each compute submit waits for the last upload (UploadManager::lastSubmit). The loads' copies have a second UploadManager on a transfer queue, with its own ring, and the frames wait only for load values the CPU saw reached (transfer queues). |
| Sharing between queues | exclusive, or concurrent | Exclusive with one queue. With a compute queue, every buffer and image is created VK_SHARING_MODE_CONCURRENT for both queue families, so nothing moves ownership. Some GPUs compress such images less (P11). With a transfer queue, buffers are concurrent for it too, and a texture filled from the ring moves to the graphics family by a release and an acquire (transfer queues). |
| Destroy with pending copies | drop them, wait for submitted ones | The same, later: destroyBuffer hands the buffer to the release queue, whose free calls cancelUploads once the frame fences and the upload fence have passed its last use (deferred destruction), so nothing waits. |
| The staging buffer's memory | system RAM | Created hostVisible. Every RASM buffer has the device-address usage bit, which VMA counts as GPU access, so VMA prefers device-local memory for it. On a GPU with a BAR heap the ring may land in VRAM. |
| Data the GPU reads every frame | one copy per frame in flight | GpuTable (the instance, material and light tables, the animated entities and the morph weight overrides): a CPU shadow, one buffer per frame slot, dirty rows per slot merged into ranges by mergeRows, uploaded in syncGpuScene after that slot's fence wait. SceneData: one hostVisible buffer per slot. See The GPU scene tables. |
| Data that only grows | write only new ranges | GeometryPool: a range allocator (RangeAllocator, first fit) over each of six device-local buffers (vertices, indices, colors, skin weights, morph deltas, the geometry table), sized from EngineConfig. The animation pool is one more, sized by EngineConfig::animationPoolBytes. A destroyed mesh's ranges come back once the GPU is done with them (deferred destruction). |
| Buffers that grow | — | Draw lists, visible draws and Hi-Z buffers are per frame slot. When one is too small, it is destroyed and a bigger one is made (draw buffers at least double), right after that slot's fence wait. Visible draws and Hi-Z grow with RenderContext::resizeBuffer, which keeps the handle, so the render graph passes that declared it stay valid; the contents and the device address change. |
| Textures | classic, or host image copy | Both, per format. RenderContext::fillTexture takes every mip (a load's are made on its worker, buildTextureLevels). Where host copy costs the GPU nothing for the format (VulkanDevice::queryFormatSupport, texture uploads), VulkanDevice::fillTexture changes the layout with vkTransitionImageLayout and copies all levels with vkCopyMemoryToImage. Otherwise, or with EngineConfig::hostImageCopy false, UploadManager::uploadTexture puts the levels in the staging ring as whole rows of blocks, 16-byte aligned, at most a chunk each, so a texture larger than the ring spans batches; copyToTextures records, per batch, UNDEFINED (the texture's first copy) or SHADER_READ_ONLY → TRANSFER_DST, the copies, and → SHADER_READ_ONLY. |
| Readback | cached memory, barrier, fence, invalidate | The same: a hostReadable buffer, readBuffer calls vmaInvalidateAllocation. updateFrameStats reads a slot's cull stats right after beginFrame waited for that slot's fence: the numbers of the slot's last frame, two frames ago. Renderer::readFrame and readTexture copy an image into a hostReadable buffer of its own, read after the fence of the frame that copied it (Headless rendering and readbacks). |
Which buffer is which kind
| Buffer | Kind | Copies | Written by |
|---|---|---|---|
| Upload staging rings | hostVisible, BufferUsage::TRANSFER | 1, or 2 with a transfer queue | UploadManager::upload |
| Scene data | hostVisible | 1 per frame slot, room for MAX_SCENE_VIEWS = 32 scene views | prepareSceneView |
| Cull stats | hostVisible + hostReadable | 1 per frame slot | the GPU; read by updateFrameStats |
| Readback buffers | hostReadable | 1 per readback, freed when it is taken | the GPU's copy; read by takeReadback |
| Instance, material and light tables, animated entities, morph weight overrides | default | 1 per frame slot | GpuTable::upload |
| Vertex, index, color, skin and morph pools, geometry table | default | 1 | GeometryPool::upload |
| Animation pool | default | 1 | Renderer::uploadMeshAnimation |
| Draw info | default | 1 per scene and frame slot | uploadDrawList |
| Visible draws, draw counts, Hi-Z, visibility | default | per scene view (and slot, except visibility) | only the GPU, except visibility's first fill |
Every buffer also gets the device-address bit and both transfer bits, whatever its BufferUsage (toVkBufferUsageFlags). So any buffer can be a copy source or destination, and can be read by a shader through its address (see Buffer device addresses).
Where it lives in code
| What | Where |
|---|---|
| Memory flags, buffer and texture creation | VulkanDevice::createBuffer, VulkanDevice::createTexture, toVkBufferUsageFlags in src/rhi/vulkan/vulkanDevice.cpp |
| The two flags | BufferDesc in include/rasm/render/resource.h; Buffer::mapped in src/rhi/device.h |
| Path choice, submit, destroy, readback | RenderContext::fillBuffer, submit, destroyBuffer, readBuffer in src/rhi/renderContext.cpp |
| Direct write and read | VulkanDevice::fillBuffer, VulkanDevice::readBuffer in src/rhi/vulkan/vulkanDevice.cpp |
| Staging ring and batches | UploadManager in src/rhi/uploadManager.h, src/rhi/uploadManager.cpp |
| Copy barriers | VulkanCommandBuffer::copyBuffers in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Per-slot tables | GpuTable, mergeRows in src/renderer/gpuTable.cpp |
| Geometry pool | GeometryPool in src/renderer/geometryPool.cpp |
| Readback buffers | recordReadbacks, takeReadback in src/renderer/readback.cpp |
| Texture upload | RenderContext::fillTexture; VulkanDevice::fillTexture (host copy) in src/rhi/vulkan/vulkanDevice.cpp; UploadManager::uploadTexture and VulkanCommandBuffer::copyToTextures (staging) |
| Tests (no GPU) | tests/uploadManagerTests.cpp, tests/gpuTableTests.cpp |
- Never
fillBuffera range that a frame in flight reads. On a mapped buffer the write lands at once, with no ordering. Use one buffer per frame slot, or a new range. - GPU scene tables are written only in
syncGpuScene, after that slot's fence wait, throughGpuTable::setRow. - Staged data arrives with the next submit, not when
fillBufferreturns. - Read only
hostReadablebuffers, and only after a barrier to the host stage and a fence wait. createBufferalways makes a new buffer (B1). Destroy the one you replace, and only when no frame in flight uses it.- Keep
MAX_CHUNK_SIZEat most a quarter ofRING_SIZE, so a skipped end plus a chunk always fit in an empty ring. - Normal, metallic-roughness and AO textures are
R8G8B8A8_UNORM; color and emissive areR8G8B8A8_SRGB.
D13: uploads are recorded on the main thread. D14: some callers ignore the result of fillBuffer.
Further reading
- The Vulkan specification, chapter "Memory Allocation": heaps, memory types and their property flags.
- AMD GPUOpen, Vulkan Memory Allocator documentation, especially "Recommended usage patterns".
- Adam Sawicki, Vulkan Memory Types on PC and How to Use Them (2021).
- Graham Sellers and John Kessenich, Vulkan Programming Guide (2016): memory and data transfer.