Recursive AI

Indirect GPU dispatch from a buffer in C#

OneGpu is a free, open-source GPU compute library for .NET from Recursive AI. MIT or Apache-2.0.

DispatchIndirect takes a GPU buffer and a byte offset. Requires Vulkan 1.3 on Windows or Linux.

Terminal
dotnet add package RecursiveAI.OneGpu.Backends
dotnet add package RecursiveAI.OneShader.Build

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

Fill.Main comes from Fill.hlsl, shown below and included in the zip.

C#
using RecursiveAI.OneGpu;
using Example.Shaders;
 
using var gpu = GpuBackends.CreateDevice();
var usage = BufferUsage.Indirect
          | BufferUsage.CopyDestination;
uint[] counts = [1, 1, 1, 2, 1, 1];
using var argsBuffer =
    gpu.CreateBuffer<uint>(counts, usage);
using var output =
    gpu.CreateBuffer<uint>([0, 0, 0, 0]);
var shader = new ShaderSource(
    ShaderStage.Compute, Fill.Main.EntryPoint)
{
    SpirV = Fill.Main.SpirV,
    Layout = Fill.Main.Layout
};
using var kernel = gpu.CreateComputeKernel(shader);
using var group = kernel.CreateBindGroup(gpu, 0,
    [BindGroupEntry.ForBuffer(0, output.Buffer)]);
var commands = gpu.BeginCommands();
var pass = commands.BeginComputePass();
pass.SetPipeline(kernel.Pipeline);
pass.SetBindGroup(0, group);
pass.DispatchIndirect(argsBuffer.Buffer, 12);
pass.EndPass();
gpu.Submit(commands);
 
var result = new uint[4];
await output.ReadAsync(result);
Console.WriteLine(string.Join(", ", result));

Reads (2, 1, 1) at byte 12, runs two workgroups, and prints:

Text
1, 2, 3, 4

Save this as Fill.hlsl beside Program.cs:

HLSL
[[vk::binding(0, 0)]]
RWStructuredBuffer<uint> Result;
[shader("compute")]
[numthreads(2, 1, 1)]
void Main(uint3 id : SV_DispatchThreadID)
{
    Result[id.x] = id.x + 1;
}

OneShader.Build generates the Fill.Main C# type. Add this setting in the console project to match the using Example.Shaders line:

XML
<PropertyGroup>
  <OneShaderNamespace>Example.Shaders</OneShaderNamespace>
</PropertyGroup>

Vulkan rejects a buffer without BufferUsage.Indirect with ArgumentException; an unaligned or out-of-range offset throws ArgumentOutOfRangeException.

Unzip the example, then dotnet run.

Variations

To dispatch one workgroup instead of two, replace the DispatchIndirect call with this one. Offset 0 selects the first (1, 1, 1) record in the same buffer:

C#
pass.DispatchIndirect(argsBuffer.Buffer, 0);
Text
1, 2, 0, 0

The short answer

Bind a compute pipeline and its resources, then call DispatchIndirect with a buffer created for indirect use and the byte offset of the count record. On Vulkan, the dispatch reads its three counts from that buffer on the GPU. C# records which buffer and offset to use; it doesn’t need to read the count values back before submission.

How does an indirect compute dispatch work?

A direct dispatch gets its workgroup counts from the call. An indirect dispatch gets them from memory. The record holds three consecutive 32-bit unsigned integers in X, Y, Z order, for a total of 12 bytes (DispatchIndirectArgs.Size). The offset must be a multiple of four and the entire record must fit. With two such records back to back, the second begins at byte 12, not byte 3 (its starting index in the uint array).

The values count workgroups, not shader threads. Here [numthreads(2, 1, 1)] sets two threads per workgroup, and (2, 1, 1) runs four shader invocations in total. Each writes a value at its own dispatch index. Picking the first record runs only two invocations; the last two entries keep the zeros uploaded at creation. If you change the counts, keep them within the device’s dispatch limits and make sure the shader doesn’t index past the output buffer. The Vulkan indirect dispatch reference describes the device-side count limits.

When should you use indirect instead of direct dispatch?

Use direct dispatch when C# already knows the counts. Use indirect dispatch when an earlier GPU operation determines how much work remains. For example, a compute pass can compact a list of active items and write the next dispatch’s workgroup counts into a buffer with both Storage and Indirect usage. The later dispatch consumes that record without a round trip to C# for the counts. OneGpu’s Vulkan encoder synchronizes indirect argument access when it records the dispatch.

The sample uploads two known records rather than running a producer shader. That lets you see exactly which record each offset selects. The only readback is after submission, to print the shader output; it isn’t part of choosing the dispatch size.

All onegpu recipes