Run C# compute kernels on CUDA, OpenCL, or the CPU from .NET 10.
Kernelium wraps ILGPU with a small API for compiling and launching kernels from C#. Pass ordinary arrays for a one-off calculation, or keep data in reusable device buffers across multiple launches. Use it for workloads such as image filters, simulations, and vector or matrix operations.
NuGet package · Source repository
Kernelium is MIT licensed and targets .NET 10.
Install Kernelium 1.0.0 in a .NET 10 project.
dotnet add package Kernelium --version 1.0.0To build against the checkout, add a project reference to Kernelium/Kernelium.csproj.
This is Kernelium's first stable release. It includes synchronous and asynchronous launches, automatic 1D and 2D launch sizing, explicit host-array transfer directions, and reusable device buffers.
Use CreateTypedKernel for compile-time argument checks,
GPUConfiguration.CudaPinnedStagingCacheBytes to tune CUDA staging, and
GPUConfiguration.ExecutionDiagnostics to observe launches.
For a fresh project, run the following commands.
dotnet new console -n KerneliumQuickstart -f net10.0
cd KerneliumQuickstart
dotnet add package Kernelium --version 1.0.0Replace Program.cs with the code below and run dotnet run. The CPU backend
makes the example runnable without a GPU.
using ILGPU;
using Kernelium;
using Kernelium.Enums;
using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu });
var add = gpu.CreateKernel(VectorAdd);
float[] left = [1f, 2f, 3f];
float[] right = [10f, 20f, 30f];
var result = new float[left.Length];
add.Execute(result.Length, left, right, result);
Console.WriteLine(string.Join(", ", result)); // 11, 22, 33
static void VectorAdd(ArrayView<float> left, ArrayView<float> right, ArrayView<float> result)
{
int i = Grid.GlobalIndex.X;
if (i < result.Length)
result[i] = left[i] + right[i];
}The example uses equal-length arrays. Kernelium can round the launch up to a full group, so the kernel checks the index before accessing the arrays.
| Backend | When to use it |
|---|---|
ComputeBackend.Auto |
Let ILGPU select the preferred available device |
ComputeBackend.Cuda |
Run on an NVIDIA GPU with CUDA support |
ComputeBackend.OpenCL |
Run on a device with a compatible OpenCL runtime |
ComputeBackend.Cpu |
Test or debug on a machine without a GPU |
Use DeviceIndex to select a device when requesting an explicit backend.
An explicit backend requires the corresponding runtime and device. GPU
construction throws if the backend or device is unavailable.
| Task | API |
|---|---|
| Select an accelerator | new GPU(new() { ComputeBackend = ComputeBackend.Cuda }) |
| Inspect the selected device | gpu.Device.Name, gpu.Device.AcceleratorType, gpu.Device.Capabilities |
| Use ILGPU directly | gpu.Accelerator |
| Compile a static C# kernel | gpu.CreateKernel(VectorAdd) |
| Check launch arguments at compile time | gpu.CreateTypedKernel<T1, T2, T3>(VectorAdd) |
| Run a one-off calculation | kernel.Execute(workItems, input, output) |
| Submit work and await completion | kernel.ExecuteAsync(workItems, input, output) |
| Keep data on the device | gpu.Upload(input), gpu.Allocate<T>(length) |
| Retrieve results | buffer.Download() or buffer.Download(destination) |
| Launch over a 2D extent | kernel.Execute2D(width, height, ...) |
| Set launch dimensions | kernel.Execute(new KernelConfig(blocks, threadsPerBlock), ...) |
The package ships llms.txt, a compact reference to the same APIs and resource rules. The quickstart for each published version is available on NuGet. NuGet README
The Kernelium 0.3.0 benchmark run on November 28, 2026 measured 72 cases on a Ryzen 7 5700G and RTX 4060 Ti. At 4096², Kernelium CUDA completed Mandelbrot in 12.11 ms versus 333.79 ms for native-threaded C#. For 4096² vector addition split into two batches, CUDA async submission averaged 11.44 ms versus 14.43 ms for serial submission. The CUDA timings include output downloads. The run covered CUDA and CPU. Run the benchmark harness from a source checkout. Full benchmark results
The GPU class represents an accelerator instance and manages kernel compilation, execution, caching and GPU memory.
gpu.Device describes the accelerator that was actually selected, including
when the configuration uses ComputeBackend.Auto.
var device = gpu.Device;
Console.WriteLine($"{device.Name} ({device.AcceleratorType})");
Console.WriteLine($"Max threads per group: {device.MaxNumThreadsPerGroup}");
Console.WriteLine($"Max group dimensions: {device.MaxGroupSize}");The device also exposes MemorySize in bytes, MaxGridSize,
MaxSharedMemoryPerGroup, WarpSize, and ILGPU's Capabilities for the
selected backend.
Use gpu.Accelerator for direct ILGPU calls, such as allocating an ILGPU
buffer and passing its view to a Kernelium kernel.
using var buffer = gpu.Accelerator.Allocate1D<int>(length);
kernel.Execute(length, (ArrayView<int>)buffer.View);This example expects a kernel with a single ArrayView<int> parameter.
GPU owns the accelerator. Keep the GPU instance alive while using it
and dispose your ILGPU buffers and streams before disposing the GPU.
Synchronous Kernelium operations use and wait for the accelerator's default stream.
Async launches use Kernelium-owned streams on CUDA and OpenCL. When issuing
direct ILGPU calls, coordinate dependencies across streams and keep the GPU and
any buffers or views alive until the work completes.
Creates a reusable kernel associated with the GPU instance.
var kernel = gpu.CreateKernel(VectorAdd);Both CreateKernel and CreateTypedKernel accept an optional
CompilationStrategy from Kernelium.Enums.
| Strategy | When the kernel compiles |
|---|---|
Eager (default) |
During kernel creation |
Lazy |
On the first launch or a call to Compile() |
Manual |
Only when explicitly compiled or already present in the GPU's shared cache |
var kernel = gpu.CreateKernel(VectorAdd, CompilationStrategy.Manual);
kernel.Compile();A manual launch throws if the cache has no compiled entry for the method.
Call Compile() again after clearing the cache.
On CUDA, define a parameterless kernel as a named static method. A parameterless lambda may compile to an instance method, which is unsupported by the compatibility wrapper for ILGPU 1.5.3.
Checks whether a kernel is present in the Kernelium compilation cache.
bool compiled = gpu.IsCompiled(VectorAdd);Removes cached entries so future launches can compile them again. In-flight launches retain their compiled kernels until their work completes.
gpu.ClearKernelCache();Closes the GPU to new work, waits for accepted work including queued launches, then releases the accelerator and its associated resources. Concurrent and repeated disposal calls report the same cleanup outcome. If a driver failure prevents Kernelium from confirming that retained work has completed, disposal throws and preserves the affected native resources until process exit.
gpu.Dispose();Using a using statement is recommended.
A Kernel represents a reusable GPU-compatible delegate associated with a specific GPU instance.
Kernel instances can be passed between classes without requiring direct access to the underlying GPU object.
Compiles the kernel or retrieves it from the compilation cache.
kernel.Compile();Indicates whether the kernel is currently cached.
bool compiled = kernel.IsCompiled;Pass host arrays directly for a one-off launch. This uses add, left,
right, and result from the quickstart.
add.Execute(result.Length, left, right, result);
// result contains [11f, 22f, 33f].Host-array arguments must be one-dimensional T[] arrays with unmanaged
elements. For a 2D workload, store the data in a flat array and index it with
the row and column. Each array argument gets its own temporary device allocation. Kernelium uploads every
array before launch and copies every array back after a successful launch, including
arrays used only as inputs. Passing the same array to multiple parameters gives each
parameter a separate allocation. Execute is synchronous and returns after the
kernel and any copy-back complete.
For one-off launches, wrap read-only inputs and fully overwritten outputs to skip unnecessary copies. The kernel still declares ordinary ILGPU array views.
add.Execute(result.Length,
ArrayArgument.Input(left),
ArrayArgument.Input(right),
ArrayArgument.Output(result));Input uploads the array and skips copying it back. Output skips uploading
the host array and downloads the result after a successful launch. The output
has unspecified initial contents, so the kernel should write every element
before download. Pass the plain array when the kernel needs both transfers.
Use ExecuteAsync(workItems, ...), ExecuteAsync(config, ...), or
Execute2DAsync(width, height, ...). Each task reports its operation's errors and
completes successfully after the kernel, host copy-back, and temporary resource cleanup.
The vector-add kernel from the quickstart can use the same stable inputs in two submissions with separate outputs.
float[] first = new float[left.Length];
float[] second = new float[left.Length];
await Task.WhenAll(
add.ExecuteAsync(first.Length, ArrayArgument.Input(left), ArrayArgument.Input(right), ArrayArgument.Output(first)),
add.ExecuteAsync(second.Length, ArrayArgument.Input(right), ArrayArgument.Input(left), ArrayArgument.Output(second)));Kernelium borrows the arrays through task completion. You may read and share input-only arrays while work is pending, and their contents must stay stable. Leave output and read/write arrays untouched until every pending use completes. A repeated array argument still gets a separate temporary device allocation for each parameter.
Kernelium orders conflicting operations by submission, including synchronous launches and buffer transfers. Uses of the same host array conflict when either operation writes, even across GPU instances. Buffer arguments, slices, and nested views conflict when they share a device allocation. Multiple host threads can submit work on every backend. CUDA and OpenCL have two async streams per GPU and can overlap independent workloads when the device and driver support it. Overlap depends on the resources each kernel uses. ILGPU runs one kernel at a time per CPU accelerator.
CUDA caches up to 128 MiB of pinned host staging per GPU instance by
default, divided among the default stream and two async streams. Allocations
are made on demand. Set a smaller total budget in bytes when creating the GPU.
using var cuda = new GPU(new()
{
ComputeBackend = ComputeBackend.Cuda,
CudaPinnedStagingCacheBytes = 48L * 1024 * 1024
});The two async streams get equal shares and the default stream gets the
remainder. Set the budget to 0 to disable caching. Transfers can still
allocate temporary pinned staging when caching is disabled or the stream's
share is exhausted. This setting applies to CUDA.
Call Execute2D(width, height, ...) to let Kernelium choose a group shape
and round up each grid dimension. Pass any dimensions the kernel needs as
ordinary arguments. This example doubles every pixel in a flat row-major image.
static void DoublePixel(int width, int height, ArrayView<int> input, ArrayView<int> output)
{
int x = Grid.GlobalIndex.X;
int y = Grid.GlobalIndex.Y;
if (x < width && y < height)
{
int offset = y * width + x;
output[offset] = input[offset] * 2;
}
}
var doublePixel = gpu.CreateKernel(DoublePixel);
var doubledPixels = new int[pixels.Length];
doublePixel.Execute2D(width, height, width, height,
ArrayArgument.Input(pixels), ArrayArgument.Output(doubledPixels));For a typed kernel whose first parameter is Index2D, pass one extent to
Execute2D(extent, ...) or Execute2DAsync(extent, ...). Kernelium uses that
extent for launch sizing and forwards it as the first kernel argument.
Both dimensions must be positive. In this example, the input and output each
contain width * height elements. Guard both coordinates because the launch
can extend past the last pixel.
Execute(workItems, ...) chooses a group size and rounds the launch up to whole
groups. workItems must be positive. Guard accesses using the relevant view lengths. If the logical workload is
smaller than the buffers, pass its length as a separate scalar and check it in the
kernel too.
Use Execute(new KernelConfig(blocks, threadsPerBlock), ...) to specify the grid and
group dimensions directly. Both dimensions must fit the selected accelerator's limits.
Upload once when the same data is used by multiple launches, and download the result when the host needs it.
using var deviceA = gpu.Upload(left);
using var deviceB = gpu.Upload(right);
using var deviceResult = gpu.Allocate<float>(result.Length);
add.Execute(result.Length, deviceA, deviceB, deviceResult);
float[] values = deviceResult.Download();Allocate<T> creates a zero-initialized buffer. Use buffer.Upload(data) to replace
its contents or buffer.Download(destination) to copy into an existing array. Both
arrays must match the buffer length. A launch with a GPUBuffer<T> uses its existing
device allocation and leaves the result there until you download it.
On CUDA, each stream reuses pinned host staging for host-array arguments and
buffer uploads. Read/write array arguments use the same staging for upload and
copy-back. Transfers that exceed the stream's cache budget use temporary staging
that is released after the stream drains. On Windows and Linux, an explicit GPUBuffer.Download uses a
blocking CUDA copy directly into the destination array.
Use a buffer or its View with the GPU instance that created it. Buffer disposal
closes the allocation to new Kernelium work, waits for accepted uses, and releases the
buffer. Concurrent and repeated disposal calls report the same cleanup outcome.
Use CreateTypedKernel for kernels with up to six parameters. Specify the
parameter types in declaration order or assign the method group to a local
variable so C# can infer the delegate type. The returned kernel's 1D, 2D, and
explicit-config launch methods check argument count and compatible types at
compile time.
var addMethod = VectorAdd;
var typedAdd = gpu.CreateTypedKernel(addMethod);
typedAdd.Execute(result.Length,
KernelArgument.Input(left), KernelArgument.Input(right), KernelArgument.Output(result));Pass scalars and ILGPU views directly. Use KernelArgument.Input, Output,
or ReadWrite for host arrays and KernelArgument.Buffer for a
GPUBuffer<T>. ReadWrite uploads the host array and copies it back.
Group related parameters into an ILGPU-compatible struct for larger typed
signatures, or use CreateKernel for an arbitrary argument count. ILGPU still
compiles and validates the kernel body at runtime.
Set ExecutionDiagnostics when constructing a GPU to receive a report after
each launch attempt, including invalid extents and arguments.
using var observed = new GPU(new()
{
ComputeBackend = ComputeBackend.Cpu,
ExecutionDiagnostics = info =>
{
Console.WriteLine(
$"{info.KernelName} on {info.DeviceName}: {info.Elapsed.TotalMilliseconds:F2} ms");
if (info.Error is not null)
Console.Error.WriteLine(info.Error.Message);
}
});The report includes the selected backend, resolved grid and group dimensions
when available, and requested upload and download bytes for host-array
arguments. Elapsed time measures the entire host-observed operation, including
queueing, compilation, transfers, and cleanup. KernelName displays the
original name for C# local functions. Kernel exposes the method metadata.
Set BufferTransferDiagnostics to observe explicit gpu.Upload,
buffer.Upload, and buffer.Download calls. Reports include the direction,
requested byte count, backend, device, host elapsed time, and any exception.
Callbacks may run concurrently and should return promptly. A callback exception does not change the operation result.
Application
|
v
Kernelium
|
+-- GPU
+-- Kernel
+-- GPUBuffer
+-- Memory Management
+-- Kernel Cache
+-- Kernel Execution
|
v
ILGPU
|
+-- CUDA
+-- OpenCL
+-- CPU
Kernelium inherits the kernel restrictions of ILGPU. GPU kernels must be compatible with ILGPU's supported subset of C#.
In particular:
- Kernels must be static methods or non-capturing lambdas that return
void. - Results are written to GPU memory.
- Managed objects and arbitrary .NET APIs cannot be used directly inside kernels.
- Hardware capabilities may differ between backends.
Kernelium handles result retrieval and resource management on the CPU side.