Recursive AI

Set Vulkan compute push constants in C#

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

Pass a multiplier to a shader with SetPushConstants before dispatch. This example needs Vulkan 1.3 on Windows or Linux.

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

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

This example also needs Scale.hlsl and the .csproj setting OneShaderNamespace, both shown below.

Program.cs

C#
using System.Runtime.InteropServices;
using RecursiveAI.OneGpu;
using RecursiveAI.OneGpu.Vulkan;
using Example.Shaders;
 
using var device = VulkanGpu.CreateDevice();
using var output = device.CreateBuffer<uint>(4);
var shader = new ShaderSource(
    ShaderStage.Compute, Scale.Main.EntryPoint)
{
    SpirV = Scale.Main.SpirV,
    Layout = Scale.Main.Layout
};
using var kernel =
    device.CreateComputeKernel(shader);
using var group = kernel.CreateBindGroup(
    device, 0,
    [BindGroupEntry.ForBuffer(0, output.Buffer)]);
var commands = device.BeginCommands();
var pass = commands.BeginComputePass();
pass.SetPipeline(kernel.Pipeline);
pass.SetBindGroup(0, group);
uint factor = 3;
var bytes = MemoryMarshal.AsBytes(
    new ReadOnlySpan<uint>(in factor));
pass.SetPushConstants(0, bytes);
pass.Dispatch(4);
pass.EndPass();
device.Submit(commands);
var values = new uint[4];
await output.ReadAsync(values);
Console.WriteLine(string.Join(", ", values));

Unzip the example, then dotnet run.

The GPU multiplies 1 through 4 by the factor and the program prints:

Text
3, 6, 9, 12

Save this as Scale.hlsl next to Program.cs. OneShader.Build generates Scale.Main from this file. Each workgroup has one invocation, so Dispatch(4) fills exactly four output elements.

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

The project pins the packages and sets the namespace used by the generated shader class:

XML
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <OneShaderNamespace>Example.Shaders</OneShaderNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="RecursiveAI.OneGpu.Vulkan" Version="1.0.0" />
    <PackageReference Include="RecursiveAI.OneShader.Build" Version="1.7.0" PrivateAssets="all" />
  </ItemGroup>
</Project>

Set the pipeline before pushing constants: otherwise the Vulkan backend throws InvalidOperationException because it has no layout for the bytes.

Variations

Use the same shader with a different multiplier by replacing the factor declaration before MemoryMarshal.AsBytes:

C#
uint factor = 5;
Text
5, 10, 15, 20

The short answer

Declare an HLSL block with [[vk::push_constant]], set the compute pipeline, and send the block’s bytes with pass.SetPushConstants before Dispatch. The offset is in bytes. This shader’s block contains one uint, so the example writes four bytes starting at offset zero. The writable output still uses a storage buffer.

What are push constants in Vulkan?

They are a small bank of values that Vulkan lets you update in a command buffer. In this example every invocation sees the same factor, but each gets a different SV_DispatchThreadID. That’s why setting the factor once is enough to compute four different results.

OneGpu’s CreateComputeKernel reads the bindings and push-constant range from shader reflection, the metadata produced when the shader is compiled. You don’t supply a second layout in C#, but you still need to match the types and offsets. MemoryMarshal.AsBytes views existing data as bytes; it doesn’t convert the values or add padding to match a shader struct. For a multi-field block, check the shader’s offsets and keep both layouts in sync. In the Vulkan backend the offset and byte count must be multiples of four, and the write must fit inside the pipeline’s declared range.

When should I use push constants instead of a uniform buffer?

Use push constants for a few values that belong to a dispatch, like the factor above or the dimensions of a calculation. For a larger parameter block, use a uniform buffer if the data fits its limits. In Vulkan, pushing the factor is part of recording the compute pass; it doesn’t require a separate buffer, upload, or resource binding for the factor. You still bind the buffer that receives the results.

The maximum available size depends on the device. Vulkan exposes it as maxPushConstantsSize, and your shader’s pipeline can declare a smaller range. Those are different checks: room on the device doesn’t make a write past the end of your declared range valid.

This download supplies SPIR-V and explicitly opens Vulkan. OneGpu’s push-constant API also works on other backends, but the shader must target the backend you use. The compute docs note that on WebGPU, OneGpu implements push constants with a uniform buffer in the highest bind group. The Vulkan example doesn’t create that binding.

All onegpu recipes