Your first compute dispatch¶
This page walks through the sample samples/compute_readback, step by step. It uploads 4096
numbers to the GPU, runs a compute shader that computes out[i] = in[i] * 3 + 0.25, and
reads the result back on the CPU. The sample covers the core RI workflow: memory, buffers,
descriptor heaps, a compute pipeline, a command list, barriers, and submission.
The same source runs on Vulkan and on D3D12: the build compiles it once per backend. It has been checked on an RTX 3080 on both backends (Windows) and on an AMD Radeon 680M with Vulkan (Linux, RADV).
The code below comes from docs/site/snippets/ri/compute.cpp, which follows the same flow
as the sample and is compiled with the documentation snippets.
Build and run it¶
Every CMake preset builds the sample:
It prints the GPU, the first four results, and how many are wrong:
ctest also runs it (as sample.compute_readback.Vulkan / .D3D12, labelled gpu).
Leak reports on Linux
The debug presets build with AddressSanitizer. Some Vulkan drivers leak a few bytes of
their own at exit, which the sanitizer reports when you run the sample by hand. ctest
passes a suppression file for those; to do the same by hand, set
LSAN_OPTIONS=suppressions=<repository>/tests/vulkan/lsan.supp.
The shader¶
The shader is HLSL. Building the sample compiles it twice with the pinned DXC compiler: to SPIR-V for Vulkan and to DXIL for D3D12 (see Compiling shaders).
#include <equine/root.hlsli>
// Root data: a few values set per dispatch with cmdSetRootData (P45).
// The C++ side declares the same struct.
struct Root {
uint inputSlot; // descriptor heap slots of the three buffers
uint outputSlot;
uint paramsSlot;
float scale;
uint count;
};
EQ_ROOT_DATA(Root, root);
EQ_ROOT_DATA declares the shader's root data: a small struct of values the C++ side sets
for each dispatch (Root data). Here it carries the heap slots of
the three buffers, the scale, and the element count.
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
if (id.x >= root.count) {
return;
}
// Bindless: fetch each buffer from the heap by the slot passed in root data.
StructuredBuffer<float> input = ResourceDescriptorHeap[root.inputSlot];
RWStructuredBuffer<float> output = ResourceDescriptorHeap[root.outputSlot];
ConstantBuffer<Params> params = ResourceDescriptorHeap[root.paramsSlot];
output[id.x] = input[id.x] * root.scale + params.offset;
}
The shader does not declare fixed resource bindings for its buffers. Instead, it fetches each
buffer from ResourceDescriptorHeap by the slot index passed in root data, which is
bindless access (Descriptor heaps).
Step 1: a device¶
First, choose a GPU from RI::listGpus and create an RI::Device on it:
RI::Device device = RI::createDevice({.gpu = chosen});
std::printf("Device created on %s\n", device.gpu.name.c_str());
See RI::listGpus and
RI::createDevice.
Step 2: memory, and buffers placed in it¶
In RI you allocate memory blocks yourself and place buffers in them at offsets you choose (Memory). First ask how much room a buffer needs:
// How much memory, at what alignment, a buffer with this description needs.
const RI::BufferDesc dataDesc{
.size = kBytes,
.usage = RI::BufferUsage::eRead | RI::BufferUsage::eReadWrite | RI::BufferUsage::eCopySrc |
RI::BufferUsage::eCopyDst,
};
const RI::MemoryRequirements dataReq = RI::bufferRequirements(device, dataDesc);
// Two such buffers side by side: the second starts at an aligned offset.
const uint64 outputOffset = alignUp(dataReq.size, dataReq.alignment);
Then allocate three blocks of different kinds: GPU memory for the data the shader works on, upload memory that the CPU writes, and readback memory that the CPU reads.
RI::Memory gpuMemory = RI::allocateMemory(device, RI::MemoryKind::eGPU, outputOffset + dataReq.size);
RI::Memory uploadMemory = RI::allocateMemory(device, RI::MemoryKind::eUpload, paramsOffset + 256);
RI::Memory readbackMemory = RI::allocateMemory(device, RI::MemoryKind::eReadback, kBytes);
Then place five buffers in those blocks. Each RI::BufferUsage flag declares how the buffer
will be used:
RI::Buffer input = RI::createBuffer(device, gpuMemory, 0, dataDesc);
RI::Buffer output = RI::createBuffer(device, gpuMemory, outputOffset, dataDesc);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopySrc});
RI::Buffer params =
RI::createBuffer(device, uploadMemory, paramsOffset, {.size = 256, .usage = RI::BufferUsage::eConstant});
RI::Buffer result = RI::createBuffer(device, readbackMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopyDst});
Step 3: write the input¶
Buffers placed in upload or readback memory stay mapped for their entire lifetime, so
you can access them directly through buffer.mapped without a separate map call. Here, the
CPU writes the input array and the shader parameter into upload memory:
// Upload memory stays mapped: write through buffer.mapped, no map call.
auto *values = static_cast<float *>(staging.mapped);
for (uint32 i = 0; i < kCount; ++i) {
values[i] = static_cast<float>(i);
}
const float offset = 0.25f;
std::memcpy(params.mapped, &offset, sizeof(offset));
The shader cannot read upload memory as fast as GPU memory, so the program will copy the
values into the input buffer on the GPU first.
Step 4: descriptors¶
Descriptors tell the GPU where buffers live and how the shader accesses them. You write descriptors into a descriptor heap at slots you choose:
// Slots are yours to choose; the shader receives them in root data.
RI::writeDescriptors(device, heap,
{{.slot = 0, .descriptor = RI::ReadView{.buffer = input, .stride = sizeof(float)}},
{.slot = 1, .descriptor = RI::ReadWriteView{.buffer = output, .stride = sizeof(float)}},
{.slot = 2, .descriptor = RI::ConstantBufferView{.buffer = params}}});
ReadView matches StructuredBuffer in the shader, ReadWriteView matches
RWStructuredBuffer, and ConstantBufferView matches ConstantBuffer. See
RI::writeDescriptors.
Step 5: the pipeline¶
A pipeline is the compiled shader, ready to run. RI reads the root data size directly from the shader bytecode, so you only pass the bytecode:
// RI takes bytecode only (P29): SPIR-V on Vulkan, DXIL on D3D12.
std::vector<std::byte> loadShader(const std::string &name) {
#if EQUINE_BACKEND_VULKAN
const std::string path = std::string(EQUINE_SHADER_DIR) + "/" + name + ".spv";
#else
const std::string path = std::string(EQUINE_SHADER_DIR) + "/" + name + ".dxil";
#endif
std::ifstream file(path, std::ios::binary);
const std::vector<char> bytes{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
std::vector<std::byte> out(bytes.size());
std::memcpy(out.data(), bytes.data(), bytes.size());
return out;
}
const std::vector<std::byte> bytecode = loadShader("doc_compute");
RI::Pipeline pipeline = RI::createComputePipeline(device, {.shader = bytecode});
// pipeline.rootDataSize is 20: the size of Root, read from the shader.
Step 6: record the commands¶
The GPU runs command lists that you record on the CPU. Recording does nothing on the GPU yet; it only writes the commands down.
Declare a matching C++ struct for the root data, with the same members in the same order
as the HLSL Root struct:
// The C++ mirror of `Root` in the shader: same members, same order.
struct Root {
uint32 inputSlot;
uint32 outputSlot;
uint32 paramsSlot;
float scale;
uint32 count;
};
RI::cmdBegin(cmd);
RI::cmdCopyBuffer(cmd, staging, 0, input, 0, kBytes);
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute); // the copy's writes, then the shader's reads
RI::cmdSetHeap(cmd, heap);
RI::cmdSetPipeline(cmd, pipeline);
RI::Helpers::cmdSetRootData(cmd, Root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount});
RI::cmdDispatch(cmd, (kCount + 63) / 64, 1, 1); // 64 threads per group, see [numthreads]
RI::cmdBarrier(cmd, RI::Stage::eCompute, RI::Stage::eCopy); // the shader's writes, then the copy's reads
RI::cmdCopyBuffer(cmd, output, 0, result, 0, kBytes);
RI::cmdEnd(cmd);
Line by line:
cmdBeginopens the list for recording.cmdCopyBuffercopies the input from upload memory to GPU memory.cmdBarrier(eCopy, eCompute): the GPU runs commands in parallel unless told otherwise. This barrier makes the shader wait until the copy has finished writing (Barriers).cmdSetHeap,cmdSetPipeline,cmdSetRootData: bind the descriptor heap, the compute pipeline, and the root data that the dispatch will use. You must callcmdSetHeapbeforecmdSetPipeline.cmdDispatchruns the shader: 64 groups of 64 threads, one thread per number.- A second barrier makes the copy wait for the shader's writes, then the result is copied to readback memory.
cmdEndcloses the list.
Step 7: submit, wait, read¶
RI::Queue &queue = device.graphicsQueue;
const RI::TimelinePoint done = RI::submit(queue, cmd);
RI::wait(queue, done); // blocks until the GPU has finished this submission
submit hands the list to the GPU and returns at once with a timeline point: a number
the GPU reaches when it has finished this work. wait blocks the CPU until then
(Timeline points). After that, the readback memory holds the
result:
// Readback memory is mapped too; after the point is reached, reads see the GPU's writes.
const auto *out = static_cast<const float *>(result.mapped);
std::printf("out[1] = %g (expected 3.25)\n", out[1]);
Step 8: clean up¶
RI destroys nothing for you: every object is destroyed explicitly, and only when the GPU no longer uses it.
// Nothing is destroyed for you, and nothing waits: the GPU is done (point reached).
RI::destroyCommandList(device, cmd);
RI::destroyPipeline(device, pipeline);
RI::destroyDescriptorHeap(device, heap);
for (RI::Buffer *buffer : {&input, &output, &staging, ¶ms, &result}) {
RI::destroyBuffer(device, *buffer);
}
RI::freeMemory(device, gpuMemory); // after the buffers placed in it
RI::freeMemory(device, uploadMemory);
RI::freeMemory(device, readbackMemory);
RI::destroyDevice(device);
The same program in Vulkan and D3D12¶
Written with the native APIs alone, the same program is several hundred lines. The full
files are docs/site/snippets/vulkan/compute.cpp and docs/site/snippets/d3d12/compute.cpp;
each reference page shows the matching part. For example, recording:
RI::cmdBegin(cmd);
RI::cmdCopyBuffer(cmd, staging, 0, input, 0, kBytes);
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute); // the copy's writes, then the shader's reads
RI::cmdSetHeap(cmd, heap);
RI::cmdSetPipeline(cmd, pipeline);
RI::Helpers::cmdSetRootData(cmd, Root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount});
RI::cmdDispatch(cmd, (kCount + 63) / 64, 1, 1); // 64 threads per group, see [numthreads]
RI::cmdBarrier(cmd, RI::Stage::eCompute, RI::Stage::eCopy); // the shader's writes, then the copy's reads
RI::cmdCopyBuffer(cmd, output, 0, result, 0, kBytes);
RI::cmdEnd(cmd);
const VkCommandBufferBeginInfo beginInfo{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
check(vkBeginCommandBuffer(cmd, &beginInfo), "vkBeginCommandBuffer");
const VkBufferCopy copyIn{.srcOffset = 0, .dstOffset = 0, .size = kBytes};
vkCmdCopyBuffer(cmd, staging, input, 1, ©In);
barrier(VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
// The same order as RI's rule: the heap first, then the pipeline.
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &heap, 0, nullptr);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
const Root root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount};
vkCmdPushConstants(cmd, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(root), &root);
vkCmdDispatch(cmd, (kCount + 63) / 64, 1, 1);
barrier(VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT,
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
const VkBufferCopy copyOut{.srcOffset = 0, .dstOffset = 0, .size = kBytes};
vkCmdCopyBuffer(cmd, output, result, 1, ©Out);
// Make the copy's writes visible to the CPU (the host stage) before ending.
barrier(VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT, VK_ACCESS_2_HOST_READ_BIT);
check(vkEndCommandBuffer(cmd), "vkEndCommandBuffer");
check(cmd->Reset(allocator.Get(), nullptr), "ID3D12GraphicsCommandList::Reset"); // opens it for recording
cmd->CopyBufferRegion(input.Get(), 0, staging.Get(), 0, kBytes); // destination first
barrier(D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_SYNC_COMPUTE_SHADING,
D3D12_BARRIER_ACCESS_SHADER_RESOURCE | D3D12_BARRIER_ACCESS_UNORDERED_ACCESS);
ID3D12DescriptorHeap *heaps[] = {viewHeap.Get(), samplerHeap.Get()};
cmd->SetDescriptorHeaps(2, heaps); // before the root signature that indexes them
cmd->SetComputeRootSignature(rootSignature.Get());
cmd->SetPipelineState(pipeline.Get());
const Root root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount};
cmd->SetComputeRoot32BitConstants(0, sizeof(root) / 4, &root, 0);
cmd->Dispatch((kCount + 63) / 64, 1, 1);
barrier(D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_SYNC_COPY,
D3D12_BARRIER_ACCESS_COPY_SOURCE);
cmd->CopyBufferRegion(result.Get(), 0, output.Get(), 0, kBytes);
// No barrier to the CPU: once the fence value is reached, mapped reads see the writes.
check(cmd->Close(), "ID3D12GraphicsCommandList::Close");