From 79038cfb3d5397f3e0325c235ea16cf9d4e52fed Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 09:55:52 +0100 Subject: [PATCH 1/9] update readme and tags --- Kernelium/Kernelium.csproj | 5 +- README.md | 94 ++++++++++++++++++-------------------- llms.txt | 20 ++++++++ 3 files changed, 68 insertions(+), 51 deletions(-) create mode 100644 llms.txt diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index 56bf891..b71550a 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -8,8 +8,8 @@ Kernelium 0.1.0-preview.1 Raphael Hinterdorfer - A lightweight .NET wrapper over ILGPU for kernel compilation, execution, and reusable device buffers. - gpu;ilgpu;cuda;opencl;compute + GPU computing for C# and .NET 10. Compile and launch ILGPU kernels on CUDA, OpenCL, or CPU with automatic array transfers and reusable device buffers. + gpu gpu-computing gpu-acceleration gpgpu csharp dotnet ilgpu cuda opencl parallel-computing https://github.com/Hinterdorfer-Raphael/Kernelium https://github.com/Hinterdorfer-Raphael/Kernelium git @@ -23,6 +23,7 @@ + diff --git a/README.md b/README.md index 3232674..350c299 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,69 @@ # Kernelium -**A simple, lightweight abstraction over ILGPU for GPU programming in C#.** +**Run C# compute kernels on CUDA, OpenCL, or the CPU from .NET 10.** -Kernelium provides an easy-to-use API for GPU computing in .NET without the need to manually manage low-level GPU resources. Built on top of [ILGPU](https://github.com/m4rs-mt/ILGPU), it simplifies kernel compilation, memory management, execution configuration and result retrieval while maintaining access to advanced GPU functionality. +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. -The goal of Kernelium is simplicity without sacrificing control. +[NuGet package](https://www.nuget.org/packages/Kernelium) · [Source repository](https://github.com/Hinterdorfer-Raphael/Kernelium) -## Features +Kernelium is in preview and is MIT licensed. The package targets .NET 10. -- Simple, instance-based GPU API -- CUDA, OpenCL and CPU backend support -- Reusable kernel instances -- Lazy and eager kernel compilation -- Kernel caching -- Automatic GPU memory management -- Automatic block and warp configuration -- Manual execution configuration -- Persistent GPU buffers -- Automatic resource cleanup +## Install -> **Development status** — Kernelium is in preview. The package targets .NET 10. - -## Getting Started +```sh +dotnet add package Kernelium --version 0.1.0-preview.1 +``` -### Initialize a GPU +## Quickstart -Automatically select an available accelerator: +Create a .NET 10 console app, install the package, and use this as `Program.cs`. The CPU backend makes the example runnable without a GPU. ```csharp using ILGPU; using Kernelium; using Kernelium.Enums; -using var gpu = new GPU(new() +using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); +var add = gpu.GenerateKernel(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 left, ArrayView right, ArrayView result) { - HardwareType = HardwareType.Auto, - DeviceIndex = 0 -}); + int i = Grid.GlobalIndex.X; + if (i < result.Length) + result[i] = left[i] + right[i]; +} ``` -### Supported Backends +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 | Hardware | +| Backend | When to use it | |---|---| -| `Auto` | Automatic device selection | -| `Cuda` | NVIDIA GPUs | -| `OpenCL` | Compatible AMD, Intel and NVIDIA GPUs | -| `Cpu` | CPU execution and debugging | +| `HardwareType.Auto` | Let ILGPU select the preferred available device | +| `HardwareType.Cuda` | Run on an NVIDIA GPU with CUDA support | +| `HardwareType.OpenCL` | Run on a device with a compatible OpenCL runtime | +| `HardwareType.Cpu` | Test or debug on a machine without a GPU | -### Define a Kernel +Use `DeviceIndex` to select a device when requesting an explicit backend. -```csharp -static void VectorAdd( - ArrayView a, - ArrayView b, - ArrayView result) -{ - int i = Grid.GlobalIndex.X; +## API at a glance - if (i < a.Length && i < b.Length && i < result.Length) - result[i] = a[i] + b[i]; -} -``` +| Task | API | +|---|---| +| Select an accelerator | `new GPU(new() { HardwareType = HardwareType.Cuda })` | +| Compile a static C# kernel | `gpu.GenerateKernel(VectorAdd)` | +| Run a one-off calculation | `kernel.Execute(workItems, input, output)` | +| Keep data on the device | `gpu.Upload(input)`, `gpu.Allocate(length)` | +| Retrieve results | `buffer.Download()` or `buffer.Download(destination)` | +| Set launch dimensions | `kernel.Execute(new KernelConfig(blocks, threadsPerBlock), ...)` | + +For coding agents generating an integration, the [NuGet readme](https://www.nuget.org/packages/Kernelium#readme) includes the complete quickstart. The package also ships `llms.txt`, a compact reference to the same APIs and resource rules. ## API Documentation @@ -77,10 +79,10 @@ Creates a reusable kernel associated with the GPU instance. var kernel = gpu.GenerateKernel(VectorAdd); ``` -Optionally compile the kernel immediately: +Kernels compile immediately by default. Pass `precompile: false` to defer compilation until the first launch: ```csharp -var kernel = gpu.GenerateKernel(VectorAdd, precompile: true); +var kernel = gpu.GenerateKernel(VectorAdd, precompile: false); ``` #### IsCompiled @@ -229,9 +231,3 @@ Kernelium handles result retrieval and resource management on the CPU side. - [ILGPU Documentation](https://ilgpu.net/docs/) - [ILGPU GitHub Repository](https://github.com/m4rs-mt/ILGPU) - [ILGPU NuGet Package](https://www.nuget.org/packages/ILGPU) - -## Project Goal - -Kernelium aims to make GPU programming in C# as straightforward as invoking an ordinary delegate, while preserving the performance and flexibility of ILGPU. - -**Simple API. Parallel execution. Full control.** diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..2ce10b0 --- /dev/null +++ b/llms.txt @@ -0,0 +1,20 @@ +# Kernelium + +> Kernelium is a .NET 10 library for running C# compute kernels with ILGPU on CUDA, OpenCL, or CPU. + +Install the public preview with `dotnet add package Kernelium --version 0.1.0-preview.1`. +Import `ILGPU`, `Kernelium`, and `Kernelium.Enums`. +Use `HardwareType.Cpu` for examples that need to work without a GPU. + +- Create an accelerator with `using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu });`. +- Define a static `void` kernel that accepts ILGPU `ArrayView` parameters and writes into an output view. Use `Grid.GlobalIndex.X` and guard the index against the logical length because launches can round up. +- Compile it with `var kernel = gpu.GenerateKernel(MyKernel);` and call `kernel.Execute(workItems, ...)`. Compilation is eager by default. Kernel execution is synchronous. +- Passing host arrays allocates a temporary device buffer per array argument, uploads each array, and copies each array back on success. +- To reuse allocations, use `gpu.Upload(input)` and `gpu.Allocate(length)`, pass the returned buffers to `Execute`, and call `output.Download()` when the host needs the result. Dispose buffers before their owning GPU. +- Keep kernel code within ILGPU's supported subset of C#. Managed objects and arbitrary .NET APIs belong on the host. + +## Documentation + +- [NuGet readme and runnable quickstart](https://www.nuget.org/packages/Kernelium#readme) +- [Kernelium source and API reference](https://github.com/Hinterdorfer-Raphael/Kernelium) +- [ILGPU documentation](https://ilgpu.net/docs/) From fcfc2e6a22a4c1ce967f973ae74382bdad39d6d6 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:07:55 +0100 Subject: [PATCH 2/9] add input and output only arguments --- Kernelium.Test/KernelExecution.cs | 24 ++++++++++++++++++++++ Kernelium/ArrayArgument.cs | 27 +++++++++++++++++++++++++ Kernelium/Memory/ParameterMarshaller.cs | 23 ++++++++++++--------- README.md | 17 ++++++++++++++++ llms.txt | 2 +- 5 files changed, 83 insertions(+), 10 deletions(-) create mode 100644 Kernelium/ArrayArgument.cs diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index 6f88bc9..fa8616a 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -45,6 +45,30 @@ public static void ExecuteKernelWithArrayView() Assert.That(data, Is.All.EqualTo(4)); } + [Test] + public static void ExecuteWithInputAndOutputArrays() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel(CopyThenClearInput); + int[] input = [3, -4, 9]; + int[] output = [-1, -1, -1]; + + kernel.Execute(input.Length, ArrayArgument.Input(input), ArrayArgument.Output(output)); + + Assert.That(output, Is.EqualTo(new[] { 3, -4, 9 })); + Assert.That(input, Is.EqualTo(new[] { 3, -4, 9 })); + } + + private static void CopyThenClearInput(ArrayView input, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < input.Length) + { + output[index] = input[index]; + input[index] = 0; + } + } + [TestCase(1)] [TestCase(10)] [TestCase(32)] diff --git a/Kernelium/ArrayArgument.cs b/Kernelium/ArrayArgument.cs new file mode 100644 index 0000000..bcb8f90 --- /dev/null +++ b/Kernelium/ArrayArgument.cs @@ -0,0 +1,27 @@ +namespace Kernelium +{ + /// Controls transfers for a host array passed to a kernel. + public sealed class ArrayArgument + { + internal Array Data { get; } + internal bool IsInput { get; } + + private ArrayArgument(Array data, bool isInput) + { + ArgumentNullException.ThrowIfNull(data); + Data = data; + IsInput = isInput; + } + + /// Uploads the array and leaves its host contents unchanged after execution. + public static ArrayArgument Input(T[] array) where T : unmanaged => + new(array, isInput: true); + + /// + /// Downloads the result into the array after execution. The kernel must + /// initialize every element because the original contents are not uploaded. + /// + public static ArrayArgument Output(T[] array) where T : unmanaged => + new(array, isInput: false); + } +} diff --git a/Kernelium/Memory/ParameterMarshaller.cs b/Kernelium/Memory/ParameterMarshaller.cs index 66d8b3a..2e0dac9 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -8,9 +8,9 @@ internal sealed class ParameterMarshaller { private readonly Accelerator accelerator; - private static readonly MethodInfo uploadMethod = + private static readonly MethodInfo marshalArrayMethod = typeof(ParameterMarshaller).GetMethod( - nameof(Upload), + nameof(MarshalArray), BindingFlags.NonPublic | BindingFlags.Instance )!; @@ -43,7 +43,8 @@ public object[] ConvertParameters( $"Kernel parameter {i} belongs to a different accelerator.", nameof(parameters)); } - if (parameter is Array array) + var arrayArgument = parameter as ArrayArgument; + if ((arrayArgument?.Data ?? parameter) is Array array) { Type type = array.GetType().GetElementType()!; @@ -52,13 +53,15 @@ public object[] ConvertParameters( "Only one-dimensional arrays are supported." ); - result[i] = uploadMethod + result[i] = marshalArrayMethod .MakeGenericMethod(type) .Invoke(this, new object[] { buffers, copyBack, - array + array, + arrayArgument is null || arrayArgument.IsInput, + arrayArgument is null || !arrayArgument.IsInput })!; } else @@ -70,18 +73,20 @@ public object[] ConvertParameters( return result; } - private ArrayView Upload( + private ArrayView MarshalArray( List buffers, List copyBack, - T[] data) where T : unmanaged + T[] data, bool copyIn, bool copyOut) where T : unmanaged { var buffer = accelerator.Allocate1D(data.Length); buffers.Add(buffer); - buffer.CopyFromCPU(data); + if (copyIn) + buffer.CopyFromCPU(data); - copyBack.Add(() => buffer.CopyToCPU(data)); + if (copyOut) + copyBack.Add(() => buffer.CopyToCPU(data)); return buffer.View; } diff --git a/README.md b/README.md index 350c299..cc76d34 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,23 @@ arrays used only as inputs. Passing the same array to multiple parameters gives parameter a separate allocation. `Execute` is synchronous and returns after the kernel and any copy-back complete. +### Choose an array transfer direction + +For one-off launches, wrap read-only inputs and fully overwritten outputs to skip +unnecessary copies. The kernel still declares ordinary ILGPU array views. + +```csharp +add.Execute(result.Length, + ArrayArgument.Input(a), + ArrayArgument.Input(b), + 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. + ### Launch dimensions `Execute(workItems, ...)` chooses a group size and rounds the launch up to whole diff --git a/llms.txt b/llms.txt index 2ce10b0..55eeee6 100644 --- a/llms.txt +++ b/llms.txt @@ -9,7 +9,7 @@ Use `HardwareType.Cpu` for examples that need to work without a GPU. - Create an accelerator with `using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu });`. - Define a static `void` kernel that accepts ILGPU `ArrayView` parameters and writes into an output view. Use `Grid.GlobalIndex.X` and guard the index against the logical length because launches can round up. - Compile it with `var kernel = gpu.GenerateKernel(MyKernel);` and call `kernel.Execute(workItems, ...)`. Compilation is eager by default. Kernel execution is synchronous. -- Passing host arrays allocates a temporary device buffer per array argument, uploads each array, and copies each array back on success. +- Passing host arrays allocates a temporary device buffer per array argument, uploads each array, and copies each array back on success. Use `ArrayArgument.Input(array)` or `ArrayArgument.Output(array)` to skip one transfer. Fully initialize output-only arrays in the kernel. - To reuse allocations, use `gpu.Upload(input)` and `gpu.Allocate(length)`, pass the returned buffers to `Execute`, and call `output.Download()` when the host needs the result. Dispose buffers before their owning GPU. - Keep kernel code within ILGPU's supported subset of C#. Managed objects and arbitrary .NET APIs belong on the host. From 7e56afca7a564f882a3226e57383dae84ed21004 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:14:07 +0100 Subject: [PATCH 3/9] add 2d execution --- Kernelium.Test/KernelExecution.cs | 39 +++++++++++++++++++++++++ Kernelium/Execution/KernelExecutor.cs | 37 +++++++++++++++++++++++ Kernelium/GPU.cs | 8 +++++ Kernelium/Kernel.cs | 4 +++ Kernelium/Memory/ParameterMarshaller.cs | 10 +++++-- README.md | 28 ++++++++++++++++++ llms.txt | 1 + 7 files changed, 124 insertions(+), 3 deletions(-) diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index fa8616a..d37a693 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -69,6 +69,45 @@ private static void CopyThenClearInput(ArrayView input, ArrayView outp } } + [TestCase(19, 23)] + [TestCase(1, 17)] + [TestCase(17, 1)] + public static void Execute2DCoversEveryCoordinate(int width, int height) + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel(DoublePixel); + int[] input = Enumerable.Range(1, width * height).ToArray(); + int[] output = new int[input.Length]; + + kernel.Execute2D(width, height, width, height, + ArrayArgument.Input(input), ArrayArgument.Output(output)); + + Assert.That(output, Is.EqualTo(input.Select(value => value * 2))); + } + + [TestCase(0, 8, "width")] + [TestCase(8, -1, "height")] + public static void Execute2DRejectsNonPositiveDimensions(int width, int height, string parameter) + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel(DoublePixel, precompile: false); + + var error = Assert.Throws(() => kernel.Execute2D(width, height)); + + Assert.That(error!.ParamName, Is.EqualTo(parameter)); + } + + private static void DoublePixel(int width, int height, ArrayView input, ArrayView 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; + } + } + [TestCase(1)] [TestCase(10)] [TestCase(32)] diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index c1ae548..d791a5f 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -79,6 +79,43 @@ public void Execute( parameters ); } + public void Execute2D( + Delegate kernel, + int width, + int height, + params object[] parameters) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + + const int tileSize = 16; + int groupSize = accelerator.EstimateGroupSize(compiler.GetOrCompile(kernel)); + var maxGroup = accelerator.MaxGroupSize; + var maxGrid = accelerator.MaxGridSize; + + int columns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); + int rows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); + columns = Math.Min(columns, groupSize); + rows = Math.Min(rows, groupSize / columns); + + var group = new Index2D(columns, rows); + var grid = new Index2D( + GetBlockCount(width, columns, maxGrid.X, nameof(width)), + GetBlockCount(height, rows, maxGrid.Y, nameof(height)) + ); + Execute(kernel, new KernelConfig(grid, group), parameters); + } + + private static int GetBlockCount(int length, int groupSize, int gridLimit, string parameterName) + { + int groups = (int)((length + (long)groupSize - 1) / groupSize); + if (groups > gridLimit || (long)groups * groupSize - 1 > int.MaxValue) + throw new ArgumentOutOfRangeException(parameterName, length, + "The workload exceeds the device grid limit with the selected group size."); + + return groups; + } + public void ExecuteOnDevice( Delegate kernel, KernelConfig config) diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index bbc6dcb..f5a97a2 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -72,6 +72,14 @@ internal void Execute( { executor.Execute(kernel, workItems, parameters); } + internal void Execute2D( + Delegate kernel, + int width, + int height, + params object[] parameters) + { + executor.Execute2D(kernel, width, height, parameters); + } internal void ExecuteOnDevice( Delegate kernel, KernelConfig config) diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index 03e0643..4cffa0d 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -15,5 +15,9 @@ public Kernel(GPU gpu, Delegate method) public void Compile() => GPU.GetOrCompile(Method); public void Execute(KernelConfig config, params object[] parameters) => GPU.Execute(Method, config, parameters); public void Execute(int workItems, params object[] parameters) => GPU.Execute(Method, workItems, parameters); + /// Launches a two-dimensional workload with an automatically sized group. + /// Guard both global indices against the logical width and height. + public void Execute2D(int width, int height, params object[] parameters) => + GPU.Execute2D(Method, width, height, parameters); } } \ No newline at end of file diff --git a/Kernelium/Memory/ParameterMarshaller.cs b/Kernelium/Memory/ParameterMarshaller.cs index 2e0dac9..c890724 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -53,6 +53,8 @@ public object[] ConvertParameters( "Only one-dimensional arrays are supported." ); + bool copyIn = arrayArgument is null || arrayArgument.IsInput; + bool copyOut = arrayArgument is null || !arrayArgument.IsInput; result[i] = marshalArrayMethod .MakeGenericMethod(type) .Invoke(this, new object[] @@ -60,8 +62,8 @@ public object[] ConvertParameters( buffers, copyBack, array, - arrayArgument is null || arrayArgument.IsInput, - arrayArgument is null || !arrayArgument.IsInput + copyIn, + copyOut })!; } else @@ -76,7 +78,9 @@ arrayArgument is null || !arrayArgument.IsInput private ArrayView MarshalArray( List buffers, List copyBack, - T[] data, bool copyIn, bool copyOut) where T : unmanaged + T[] data, + bool copyIn, + bool copyOut) where T : unmanaged { var buffer = accelerator.Allocate1D(data.Length); diff --git a/README.md b/README.md index cc76d34..d25e774 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ Use `DeviceIndex` to select a device when requesting an explicit backend. | Run a one-off calculation | `kernel.Execute(workItems, input, output)` | | Keep data on the device | `gpu.Upload(input)`, `gpu.Allocate(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), ...)` | For coding agents generating an integration, the [NuGet readme](https://www.nuget.org/packages/Kernelium#readme) includes the complete quickstart. The package also ships `llms.txt`, a compact reference to the same APIs and resource rules. @@ -170,6 +171,33 @@ 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. +### Launch a 2D workload + +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. + +```csharp +static void DoublePixel(int width, int height, ArrayView input, ArrayView 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.GenerateKernel(DoublePixel); +doublePixel.Execute2D(width, height, width, height, + ArrayArgument.Input(pixels), ArrayArgument.Output(result)); +``` + +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. + ### Launch dimensions `Execute(workItems, ...)` chooses a group size and rounds the launch up to whole diff --git a/llms.txt b/llms.txt index 55eeee6..d58e9e8 100644 --- a/llms.txt +++ b/llms.txt @@ -9,6 +9,7 @@ Use `HardwareType.Cpu` for examples that need to work without a GPU. - Create an accelerator with `using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu });`. - Define a static `void` kernel that accepts ILGPU `ArrayView` parameters and writes into an output view. Use `Grid.GlobalIndex.X` and guard the index against the logical length because launches can round up. - Compile it with `var kernel = gpu.GenerateKernel(MyKernel);` and call `kernel.Execute(workItems, ...)`. Compilation is eager by default. Kernel execution is synchronous. +- Use `kernel.Execute2D(width, height, ...)` for automatic 2D launch sizing. In the kernel, guard `Grid.GlobalIndex.X` and `.Y` before indexing a flat row-major array with `y * width + x`. Pass any dimensions the kernel needs as separate arguments. - Passing host arrays allocates a temporary device buffer per array argument, uploads each array, and copies each array back on success. Use `ArrayArgument.Input(array)` or `ArrayArgument.Output(array)` to skip one transfer. Fully initialize output-only arrays in the kernel. - To reuse allocations, use `gpu.Upload(input)` and `gpu.Allocate(length)`, pass the returned buffers to `Execute`, and call `output.Download()` when the host needs the result. Dispose buffers before their owning GPU. - Keep kernel code within ILGPU's supported subset of C#. Managed objects and arbitrary .NET APIs belong on the host. From 39e675375b27f1d275593a045f77b78aee8684f5 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:23:49 +0100 Subject: [PATCH 4/9] expose selected device for a gpu instance and access to the underlying accelerator --- Kernelium.Test/GPUInit.cs | 22 ++++++++++++-- Kernelium/GPU.cs | 8 +++++ README.md | 34 +++++++++++++++++++++ llms.txt | 63 +++++++++++++++++++++++++++++++-------- 4 files changed, 112 insertions(+), 15 deletions(-) diff --git a/Kernelium.Test/GPUInit.cs b/Kernelium.Test/GPUInit.cs index 0770bb8..6b6f1ea 100644 --- a/Kernelium.Test/GPUInit.cs +++ b/Kernelium.Test/GPUInit.cs @@ -1,7 +1,5 @@ using ILGPU; -using System; -using System.Collections.Generic; -using System.Text; +using ILGPU.Runtime; namespace Kernelium.Test { @@ -20,6 +18,24 @@ public static void TryInit() }); }); } + [Test] + public static void UseSelectedAcceleratorWithKernelium() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var accelerator = gpu.Accelerator; + + Assert.That(gpu.Device, Is.SameAs(accelerator.Device)); + Assert.That(gpu.Device.AcceleratorType, Is.EqualTo(AcceleratorType.CPU)); + Assert.That(gpu.Device.Name, Is.Not.Empty); + Assert.That(gpu.Device.MaxNumThreadsPerGroup, Is.Positive); + + using var buffer = accelerator.Allocate1D(4); + var kernel = gpu.GenerateKernel(TestHelper.Fill); + kernel.Execute(4, (ArrayView)buffer.View, 42); + + Assert.That(buffer.GetAsArray1D(), Is.All.EqualTo(42)); + } + [Test] public static void TryInitKernel() { diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index f5a97a2..a12ba2e 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -18,6 +18,14 @@ public class GPU : IDisposable private readonly KernelCompiler compiler; private readonly KernelExecutor executor; private readonly ParameterMarshaller marshaller; + + /// Information and capabilities for the selected device. + public Device Device => accelerator.Device; + + /// The ILGPU accelerator owned by this GPU instance. + /// Dispose this GPU instance to release the accelerator. + public Accelerator Accelerator => accelerator; + public GPU(GPUConfiguration? config = null) { context = Context.CreateDefault(); diff --git a/README.md b/README.md index d25e774..d4f7c90 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ Use `DeviceIndex` to select a device when requesting an explicit backend. | Task | API | |---|---| | Select an accelerator | `new GPU(new() { HardwareType = HardwareType.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.GenerateKernel(VectorAdd)` | | Run a one-off calculation | `kernel.Execute(workItems, input, output)` | | Keep data on the device | `gpu.Upload(input)`, `gpu.Allocate(length)` | @@ -72,6 +74,38 @@ For coding agents generating an integration, the [NuGet readme](https://www.nuge The `GPU` class represents an accelerator instance and manages kernel compilation, execution, caching and GPU memory. +#### Inspect the selected device + +`gpu.Device` describes the accelerator that was actually selected, including +when the configuration uses `HardwareType.Auto`. + +```csharp +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 the underlying ILGPU accelerator + +Use `gpu.Accelerator` for direct ILGPU calls, such as allocating an ILGPU +buffer and passing its view to a Kernelium kernel. + +```csharp +using var buffer = gpu.Accelerator.Allocate1D(length); +kernel.Execute(length, (ArrayView)buffer.View); +``` + +This example expects a kernel with a single `ArrayView` parameter. +`GPU` owns the accelerator. Keep the `GPU` instance alive while using it +and dispose your ILGPU buffers and streams before disposing the `GPU`. +Kernelium launches on the accelerator's default stream. Synchronize any +work on a custom stream before a Kernelium launch that depends on it. + #### GenerateKernel Creates a reusable kernel associated with the GPU instance. diff --git a/llms.txt b/llms.txt index d58e9e8..32ff801 100644 --- a/llms.txt +++ b/llms.txt @@ -1,21 +1,60 @@ # Kernelium -> Kernelium is a .NET 10 library for running C# compute kernels with ILGPU on CUDA, OpenCL, or CPU. +> Kernelium is an MIT-licensed .NET 10 library for running C# compute kernels with ILGPU on CUDA, OpenCL, or CPU. Use host arrays for simple launches and reusable device buffers for repeated work. -Install the public preview with `dotnet add package Kernelium --version 0.1.0-preview.1`. -Import `ILGPU`, `Kernelium`, and `Kernelium.Enums`. -Use `HardwareType.Cpu` for examples that need to work without a GPU. +## Install and check the version -- Create an accelerator with `using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu });`. -- Define a static `void` kernel that accepts ILGPU `ArrayView` parameters and writes into an output view. Use `Grid.GlobalIndex.X` and guard the index against the logical length because launches can round up. -- Compile it with `var kernel = gpu.GenerateKernel(MyKernel);` and call `kernel.Execute(workItems, ...)`. Compilation is eager by default. Kernel execution is synchronous. -- Use `kernel.Execute2D(width, height, ...)` for automatic 2D launch sizing. In the kernel, guard `Grid.GlobalIndex.X` and `.Y` before indexing a flat row-major array with `y * width + x`. Pass any dimensions the kernel needs as separate arguments. -- Passing host arrays allocates a temporary device buffer per array argument, uploads each array, and copies each array back on success. Use `ArrayArgument.Input(array)` or `ArrayArgument.Output(array)` to skip one transfer. Fully initialize output-only arrays in the kernel. -- To reuse allocations, use `gpu.Upload(input)` and `gpu.Allocate(length)`, pass the returned buffers to `Execute`, and call `output.Download()` when the host needs the result. Dispose buffers before their owning GPU. -- Keep kernel code within ILGPU's supported subset of C#. Managed objects and arbitrary .NET APIs belong on the host. +- `dotnet add package Kernelium --version 0.1.0-preview.1` installs the first public preview. +- The quickstart and reusable buffers below work with that preview. `ArrayArgument.Input`, `ArrayArgument.Output`, `Execute2D`, `GPU.Device`, and `GPU.Accelerator` were added after `0.1.0-preview.1`. Check the referenced package version before using them. + +## Quickstart + +Use this as `Program.cs` in a .NET 10 console app. The CPU backend runs without a GPU. + +```csharp +using ILGPU; +using Kernelium; +using Kernelium.Enums; + +using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); +var kernel = gpu.GenerateKernel(DoubleValues); + +int[] input = [1, 2, 3]; +var output = new int[input.Length]; +kernel.Execute(output.Length, input, output); + +Console.WriteLine(string.Join(", ", output)); // 2, 4, 6 + +static void DoubleValues(ArrayView input, ArrayView output) +{ + int i = Grid.GlobalIndex.X; + if (i < output.Length) + output[i] = input[i] * 2; +} +``` + +## Launches and device selection + +- Set `HardwareType.Cuda` for a CUDA-capable NVIDIA device, `HardwareType.OpenCL` for a compatible OpenCL runtime, or `HardwareType.Auto` for ILGPU's preferred available device. `DeviceIndex` selects a device for an explicit backend. +- `GenerateKernel` compiles eagerly by default. Use `precompile: false` to defer compilation. `Execute` returns after the kernel and any copy-back complete. +- `kernel.Execute(count, ...)` sizes a 1D launch. `kernel.Execute2D(width, height, ...)` sizes a 2D launch. Pass dimensions again as kernel arguments if the kernel needs them, for example `kernel.Execute2D(width, height, width, height, input, output)`. +- Launches may round up to a full group. Guard each global index against the logical extent. For a flat row-major image, guard both `x` and `y` before indexing with `y * width + x`. +- Use the `KernelConfig` overload for explicit grid and group dimensions. Kernel methods use ILGPU's supported subset of C# and write results through `ArrayView`. + +## Transfers and resource ownership + +- A plain `T[]` gets a temporary device buffer, an upload, and a copy-back on success. With `ArrayArgument.Input(array)` only the upload happens. With `ArrayArgument.Output(array)` only the copy-back happens, so the kernel needs to initialize the entire output. +- For repeated launches, use `using var source = gpu.Upload(input);` and `using var destination = gpu.Allocate(output.Length);`. Pass both buffers to `Execute` and call `destination.Download(output)` when the host needs the result. +- Use buffers with the GPU that created them and dispose them before that GPU. Keep intermediate results on the device across launches to avoid repeated allocations and transfers. + +## ILGPU interop + +- `gpu.Device` reports the actual selected backend and device name, along with memory size, grid and group limits, and backend capabilities. +- `gpu.Accelerator` is the underlying ILGPU accelerator. The `GPU` instance owns it. Dispose any buffers and streams you create before disposing `GPU`. +- Pass compatible ILGPU views from the same accelerator to Kernelium. Kernelium launches on the default stream. Synchronize dependent work submitted to a custom stream before launching a Kernelium kernel that uses its results. ## Documentation -- [NuGet readme and runnable quickstart](https://www.nuget.org/packages/Kernelium#readme) +- [NuGet package and published quickstart](https://www.nuget.org/packages/Kernelium#readme) - [Kernelium source and API reference](https://github.com/Hinterdorfer-Raphael/Kernelium) - [ILGPU documentation](https://ilgpu.net/docs/) From 6cba67e5796fbcbf3f4f5dafc39a5d3a375d4a07 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:30:03 +0100 Subject: [PATCH 5/9] fix silent Kernel init fail bug and large cpu 2d executions fixed and fixed accelerator cleanup issue --- Kernelium.Test/KernelExecution.cs | 11 +++++ Kernelium/Execution/KernelExecutor.cs | 28 ++++++++--- Kernelium/GPU.cs | 71 +++++++++++++++++++-------- Kernelium/Kernel.cs | 3 ++ 4 files changed, 87 insertions(+), 26 deletions(-) diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index d37a693..4c6b13f 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -18,6 +18,17 @@ public static void ExecuteKernel() kernel.Execute(new KernelConfig(1, 1), 42)); } + [Test] + public static void BothKernelEntryPointsRejectMulticastDelegates() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + Action> kernel = TestHelper.Increment; + kernel += TestHelper.Square; + + Assert.Throws(() => new Kernel(gpu, kernel)); + Assert.Throws(() => gpu.GenerateKernel(kernel)); + } + [Test] public static void ExecuteKernelWithoutParameters() { diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index d791a5f..9cf93c9 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -89,14 +89,27 @@ public void Execute2D( ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); const int tileSize = 16; - int groupSize = accelerator.EstimateGroupSize(compiler.GetOrCompile(kernel)); + var compiled = compiler.GetOrCompile(kernel); + int maxGroupSize = accelerator.MaxNumThreadsPerGroup; + if (compiled.Specialization.MaxNumThreadsPerGroup is int kernelLimit) + maxGroupSize = Math.Min(maxGroupSize, kernelLimit); var maxGroup = accelerator.MaxGroupSize; var maxGrid = accelerator.MaxGridSize; - int columns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); - int rows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); - columns = Math.Min(columns, groupSize); - rows = Math.Min(rows, groupSize / columns); + int minimumColumns = DivideRoundUp(width, maxGrid.X); + int minimumRows = DivideRoundUp(height, maxGrid.Y); + if (minimumColumns > Math.Min(maxGroup.X, maxGroupSize)) + throw new ArgumentOutOfRangeException(nameof(width), width, "The workload exceeds the device grid limit."); + if (minimumRows > Math.Min(maxGroup.Y, maxGroupSize / minimumColumns)) + throw new ArgumentOutOfRangeException(nameof(height), height, "The workload exceeds the device grid limit."); + + int minimumGroupSize = minimumColumns * minimumRows; + int preferredGroupSize = Math.Min(accelerator.EstimateGroupSize(compiled), maxGroupSize); + int groupSize = minimumGroupSize > preferredGroupSize ? maxGroupSize : preferredGroupSize; + int preferredColumns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); + int preferredRows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); + int columns = Math.Clamp(preferredColumns, minimumColumns, groupSize / minimumRows); + int rows = Math.Clamp(preferredRows, minimumRows, groupSize / columns); var group = new Index2D(columns, rows); var grid = new Index2D( @@ -108,7 +121,7 @@ public void Execute2D( private static int GetBlockCount(int length, int groupSize, int gridLimit, string parameterName) { - int groups = (int)((length + (long)groupSize - 1) / groupSize); + int groups = DivideRoundUp(length, groupSize); if (groups > gridLimit || (long)groups * groupSize - 1 > int.MaxValue) throw new ArgumentOutOfRangeException(parameterName, length, "The workload exceeds the device grid limit with the selected group size."); @@ -116,6 +129,9 @@ private static int GetBlockCount(int length, int groupSize, int gridLimit, strin return groups; } + private static int DivideRoundUp(int length, int divisor) => + (int)((length + (long)divisor - 1) / divisor); + public void ExecuteOnDevice( Delegate kernel, KernelConfig config) diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index a12ba2e..e024fa9 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -29,26 +29,33 @@ public class GPU : IDisposable public GPU(GPUConfiguration? config = null) { context = Context.CreateDefault(); - config ??= new GPUConfiguration(); - accelerator = config.HardwareType switch + try { - HardwareType.Cuda =>context.CreateCudaAccelerator(config.DeviceIndex), - HardwareType.OpenCL =>context.CreateCLAccelerator(config.DeviceIndex), - HardwareType.Cpu =>context.CreateCPUAccelerator(config.DeviceIndex), - HardwareType.Auto =>context.GetPreferredDevice(false).CreateAccelerator(context), - _ => throw new NotSupportedException() - }; - compiler = new KernelCompiler(accelerator); - marshaller = new ParameterMarshaller(accelerator); - executor = new KernelExecutor( - accelerator, - compiler, - marshaller - ); + config ??= new GPUConfiguration(); + accelerator = config.HardwareType switch + { + HardwareType.Cuda => context.CreateCudaAccelerator(config.DeviceIndex), + HardwareType.OpenCL => context.CreateCLAccelerator(config.DeviceIndex), + HardwareType.Cpu => context.CreateCPUAccelerator(config.DeviceIndex), + HardwareType.Auto => context.GetPreferredDevice(false).CreateAccelerator(context), + _ => throw new NotSupportedException() + }; + compiler = new KernelCompiler(accelerator); + marshaller = new ParameterMarshaller(accelerator); + executor = new KernelExecutor( + accelerator, + compiler, + marshaller + ); + } + catch + { + DisposeAcceleratorAndContext(); + throw; + } } public Kernel GenerateKernel(Delegate kernel, bool precompile = true) { - KernelCompiler.ValidateKernel(kernel); var instance = new Kernel(this, kernel); if (precompile) instance.Compile(); @@ -138,10 +145,34 @@ public GPUBuffer Upload(T[] data) where T : unmanaged } public void Dispose() { - accelerator.Synchronize(); - compiler.Clear(); - accelerator.Dispose(); - context.Dispose(); + try + { + if (!accelerator.IsDisposed) + accelerator.Synchronize(); + } + finally + { + try + { + compiler.Clear(); + } + finally + { + DisposeAcceleratorAndContext(); + } + } + } + + private void DisposeAcceleratorAndContext() + { + try + { + accelerator?.Dispose(); + } + finally + { + context.Dispose(); + } } } } diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index 4cffa0d..1ac9fa0 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -1,4 +1,5 @@ using ILGPU; +using Kernelium.Compilation; namespace Kernelium { @@ -9,6 +10,8 @@ public class Kernel public bool IsCompiled => GPU.IsCompiled(Method); public Kernel(GPU gpu, Delegate method) { + ArgumentNullException.ThrowIfNull(gpu); + KernelCompiler.ValidateKernel(method); GPU = gpu; Method = method; } From 454abf2fca63fb18d3dad9600d0e6cec0afa7505 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:39:04 +0100 Subject: [PATCH 6/9] fix parameterless kernel execution that behave differently on the 3 backends --- Kernelium.Test/KernelExecution.cs | 45 +++++++++++++++++++++++++ Kernelium/Compilation/KernelCompiler.cs | 5 ++- Kernelium/Compilation/KernelWrapper.cs | 31 +++++++---------- Kernelium/Execution/KernelExecutor.cs | 35 +++++++++++++------ README.md | 4 +++ 5 files changed, 90 insertions(+), 30 deletions(-) diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index 4c6b13f..eef6b3e 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -1,4 +1,5 @@ using ILGPU; +using ILGPU.Runtime; using ILGPU.Runtime.Cuda; namespace Kernelium.Test @@ -41,6 +42,50 @@ public static void ExecuteKernelWithoutParameters() kernel.Execute(new KernelConfig(1, 1))); } + [TestCase(Enums.HardwareType.Cuda, AcceleratorType.Cuda)] + [TestCase(Enums.HardwareType.OpenCL, AcceleratorType.OpenCL)] + public static void ExecuteParameterlessKernelOnGpu( + Enums.HardwareType hardwareType, + AcceleratorType acceleratorType) + { + using var context = Context.CreateDefault(); + if (!context.Devices.Any(device => device.AcceleratorType == acceleratorType)) + Assert.Ignore($"{acceleratorType} accelerator unavailable."); + + using var gpu = new GPU(new() { HardwareType = hardwareType }); + var kernel = gpu.GenerateKernel(TestHelper.NoParameters); + Assert.DoesNotThrow(() => kernel.Execute(1)); + + gpu.ClearKernelCache(); + Assert.DoesNotThrow(() => kernel.Execute(1)); + + if (acceleratorType == AcceleratorType.OpenCL) + { + var lambda = gpu.GenerateKernel((Action)(static () => { })); + Assert.DoesNotThrow(() => lambda.Execute(1)); + } + } + + [Test] + public static void ExecuteParameterlessLambda() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel((Action)(static () => { })); + + Assert.DoesNotThrow(() => kernel.Execute(1)); + } + + [Test] + public static void ExecuteRejectsNullArgumentList() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel(TestHelper.NoParameters); + + var error = Assert.Throws(() => kernel.Execute(1, null!)); + + Assert.That(error!.ParamName, Is.EqualTo("parameters")); + } + [Test] public static void ExecuteKernelWithArrayView() { diff --git a/Kernelium/Compilation/KernelCompiler.cs b/Kernelium/Compilation/KernelCompiler.cs index f35a3c5..323b191 100644 --- a/Kernelium/Compilation/KernelCompiler.cs +++ b/Kernelium/Compilation/KernelCompiler.cs @@ -19,7 +19,10 @@ public ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) { if (!kernelCache.TryGetValue(kernel.Method,out var compiled)) { - MethodInfo method = KernelWrapper.Wrap(kernel.Method); + MethodInfo method = kernel.Method; + // ILGPU 1.5.3's CUDA launcher assumes at least one parameter. + if (accelerator.AcceleratorType == AcceleratorType.Cuda && method.GetParameters().Length == 0) + method = KernelWrapper.WrapForCuda(method); compiled = accelerator.LoadKernel(method); kernelCache.Add(kernel.Method, compiled); } diff --git a/Kernelium/Compilation/KernelWrapper.cs b/Kernelium/Compilation/KernelWrapper.cs index ec762c3..b562a57 100644 --- a/Kernelium/Compilation/KernelWrapper.cs +++ b/Kernelium/Compilation/KernelWrapper.cs @@ -6,14 +6,22 @@ namespace Kernelium.Compilation { internal static class KernelWrapper { - public static MethodInfo Wrap(MethodInfo kernel) + private static readonly ConditionalWeakTable wrappers = new(); + + public static MethodInfo WrapForCuda(MethodInfo kernel) { - if (kernel.GetParameters().Length != 0) - return kernel; + if (!kernel.IsStatic) + throw new NotSupportedException( + "CUDA requires a static method for a parameterless kernel. Use a named static method or add a kernel parameter."); + + return wrappers.GetValue(kernel, CreateWrapper); + } + private static MethodInfo CreateWrapper(MethodInfo kernel) + { var assembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName($"Kernelium_{Guid.NewGuid():N}"), - AssemblyBuilderAccess.Run + AssemblyBuilderAccess.RunAndCollect ); var accessAttribute = typeof(IgnoresAccessChecksToAttribute) .GetConstructor(new[] { typeof(string) })!; @@ -47,20 +55,5 @@ public static MethodInfo Wrap(MethodInfo kernel) return type.CreateType()!.GetMethod("Execute")!; } - - public static object[] ConvertArguments(MethodInfo kernel, object[] parameters) - { - int expected = kernel.GetParameters().Length; - - if (parameters.Length != expected) - throw new ArgumentException( - $"Kernel expects {expected} parameters, " + - $"but {parameters.Length} were provided." - ); - - if (expected == 0) - return new object[] { 0 }; - return parameters; - } } } diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index 9cf93c9..c210c31 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -28,10 +28,7 @@ public void Execute( List copyBack = new(); try { - parameters = KernelWrapper.ConvertArguments( - kernel.Method, - parameters - ); + ValidateArguments(kernel, parameters); var compiled = compiler.GetOrCompile(kernel); object[] gpuParameters = marshaller.ConvertParameters( @@ -42,7 +39,7 @@ public void Execute( compiled.Launch( accelerator.DefaultStream, config, - gpuParameters + GetLaunchArguments(compiled, gpuParameters) ); accelerator.Synchronize(); foreach (var copy in copyBack) @@ -132,19 +129,37 @@ private static int GetBlockCount(int length, int groupSize, int gridLimit, strin private static int DivideRoundUp(int length, int divisor) => (int)((length + (long)divisor - 1) / divisor); + private static void ValidateArguments(Delegate kernel, object[] parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + int expected = kernel.Method.GetParameters().Length; + if (parameters.Length != expected) + throw new ArgumentException( + $"Kernel expects {expected} parameters, but {parameters.Length} were provided.", + nameof(parameters)); + } + + private object[] GetLaunchArguments(ILGPU.Runtime.Kernel compiled, object[] arguments) + { + // CUDA's parameterless wrapper has one unused argument. + if (accelerator.AcceleratorType == AcceleratorType.Cuda && + arguments.Length == 0 && compiled.NumParameters == 1) + return new object[] { 0 }; + + return arguments; + } + public void ExecuteOnDevice( Delegate kernel, KernelConfig config) { - object[] parameters = KernelWrapper.ConvertArguments( - kernel.Method, - Array.Empty() - ); + object[] parameters = Array.Empty(); + ValidateArguments(kernel, parameters); var compiled = compiler.GetOrCompile(kernel); compiled.Launch( accelerator.DefaultStream, config, - parameters + GetLaunchArguments(compiled, parameters) ); } } diff --git a/README.md b/README.md index d4f7c90..e5024df 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,10 @@ Kernels compile immediately by default. Pass `precompile: false` to defer compil var kernel = gpu.GenerateKernel(VectorAdd, precompile: false); ``` +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. + #### IsCompiled Checks whether a kernel is present in the Kernelium compilation cache. From dc6f4c7296c8622b52c6bc4d73613d704fab2486 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 10:46:52 +0100 Subject: [PATCH 7/9] Simplify kernel dispatch and validate launch limits and buffer ownership --- Kernelium.Test/GPUBufferTests.cs | 40 ++++++- Kernelium.Test/KernelExecution.cs | 12 ++ Kernelium/Execution/KernelExecutor.cs | 146 ++++++++++++------------ Kernelium/GPU.cs | 6 - Kernelium/Memory/ParameterMarshaller.cs | 81 ++++++++----- 5 files changed, 173 insertions(+), 112 deletions(-) diff --git a/Kernelium.Test/GPUBufferTests.cs b/Kernelium.Test/GPUBufferTests.cs index 1b8c9a8..caddd43 100644 --- a/Kernelium.Test/GPUBufferTests.cs +++ b/Kernelium.Test/GPUBufferTests.cs @@ -4,7 +4,7 @@ namespace Kernelium.Test { [TestFixture] - internal static class GPUBufferTests + public static class GPUBufferTests { private static GPU CreateGpu() => new(new() { HardwareType = HardwareType.Cpu }); @@ -145,5 +145,43 @@ public static void KernelRejectsBufferFromDifferentAccelerator(bool useView) kernel.Execute(new KernelConfig(1, 1), useView ? (object)buffer.View : buffer)); Assert.That(buffer.Download(), Is.EqualTo(new[] { 1 })); } + + [Test] + public static void KernelValidatesNestedViewOwnership() + { + using var gpu = CreateGpu(); + using var otherGpu = CreateGpu(); + using var local = gpu.Upload(new[] { 3 }); + using var foreign = otherGpu.Upload(new[] { 7 }); + var kernel = gpu.GenerateKernel(IncrementNestedView); + var argument = new NestedView(new BufferView(local.View)); + + kernel.Execute(1, argument); + Assert.That(local.Download(), Is.EqualTo(new[] { 4 })); + + Assert.Throws(() => + kernel.Execute(1, new NestedView(new BufferView(foreign.View)))); + Assert.That(foreign.Download(), Is.EqualTo(new[] { 7 })); + + local.Dispose(); + Assert.Throws(() => kernel.Execute(1, argument)); + } + + private static void IncrementNestedView(NestedView argument) + { + int index = Grid.GlobalIndex.X; + if (index < argument.Buffer.View.Length) + argument.Buffer.View[index]++; + } + + public readonly struct NestedView(BufferView buffer) + { + public readonly BufferView Buffer = buffer; + } + + public readonly struct BufferView(ArrayView view) + { + public readonly ArrayView View = view; + } } } diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index eef6b3e..2b84c35 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -141,6 +141,18 @@ public static void Execute2DCoversEveryCoordinate(int width, int height) Assert.That(output, Is.EqualTo(input.Select(value => value * 2))); } + [Test] + public static void CpuRejectsLaunchesWithTooManyPaddedThreads() + { + using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + var kernel = gpu.GenerateKernel(TestHelper.NoParameters); + + Assert.Throws(() => kernel.Execute2D(131_072, 32_768)); + + var config = new KernelConfig(new Index3D(1_024, 1_024, 4_096), new Index3D(1, 1, 1)); + Assert.Throws(() => kernel.Execute(config)); + } + [TestCase(0, 8, "width")] [TestCase(8, -1, "height")] public static void Execute2DRejectsNonPositiveDimensions(int width, int height, string parameter) diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index c210c31..a9b5868 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -19,62 +19,24 @@ public KernelExecutor( this.compiler = compiler; this.marshaller = marshaller; } - public void Execute( - Delegate kernel, - KernelConfig config, - params object[] parameters) + public void Execute(Delegate kernel, KernelConfig config, params object[] parameters) { - List buffers = new(); - List copyBack = new(); - try - { - ValidateArguments(kernel, parameters); - var compiled = compiler.GetOrCompile(kernel); - object[] gpuParameters = - marshaller.ConvertParameters( - buffers, - copyBack, - parameters - ); - compiled.Launch( - accelerator.DefaultStream, - config, - GetLaunchArguments(compiled, gpuParameters) - ); - accelerator.Synchronize(); - foreach (var copy in copyBack) - copy(); - } - finally - { - try - { - accelerator.Synchronize(); - } - finally - { - foreach (var buffer in buffers) - buffer.Dispose(); - } - } + ValidateArguments(kernel, parameters); + Launch(compiler.GetOrCompile(kernel), config, parameters); } + public void Execute( Delegate kernel, int workItems, params object[] parameters) { - ArgumentOutOfRangeException - .ThrowIfNegativeOrZero(workItems); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems); + ValidateArguments(kernel, parameters); + var compiled = compiler.GetOrCompile(kernel); int threads = accelerator.EstimateGroupSize(compiled); - int blocks = (int)( - (workItems + (long)threads - 1) / threads - ); - Execute( - kernel, - new KernelConfig(blocks, threads), - parameters - ); + int blocks = DivideRoundUp(workItems, threads); + Launch(compiled, new KernelConfig(blocks, threads), parameters); } public void Execute2D( Delegate kernel, @@ -84,12 +46,18 @@ public void Execute2D( { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + ValidateArguments(kernel, parameters); const int tileSize = 16; var compiled = compiler.GetOrCompile(kernel); int maxGroupSize = accelerator.MaxNumThreadsPerGroup; if (compiled.Specialization.MaxNumThreadsPerGroup is int kernelLimit) maxGroupSize = Math.Min(maxGroupSize, kernelLimit); + int preferredGroupSize = Math.Min(accelerator.EstimateGroupSize(compiled), maxGroupSize); + // On OpenCL this query returns a per-kernel limit. + if (accelerator.AcceleratorType == AcceleratorType.OpenCL) + maxGroupSize = preferredGroupSize; + var maxGroup = accelerator.MaxGroupSize; var maxGrid = accelerator.MaxGridSize; @@ -101,7 +69,6 @@ public void Execute2D( throw new ArgumentOutOfRangeException(nameof(height), height, "The workload exceeds the device grid limit."); int minimumGroupSize = minimumColumns * minimumRows; - int preferredGroupSize = Math.Min(accelerator.EstimateGroupSize(compiled), maxGroupSize); int groupSize = minimumGroupSize > preferredGroupSize ? maxGroupSize : preferredGroupSize; int preferredColumns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); int preferredRows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); @@ -113,7 +80,47 @@ public void Execute2D( GetBlockCount(width, columns, maxGrid.X, nameof(width)), GetBlockCount(height, rows, maxGrid.Y, nameof(height)) ); - Execute(kernel, new KernelConfig(grid, group), parameters); + Launch(compiled, new KernelConfig(grid, group), parameters); + } + + private void Launch( + ILGPU.Runtime.Kernel compiled, + KernelConfig config, + object[] parameters) + { + ValidateCpuLaunchSize(config); + List buffers = new(); + List copyBack = new(); + try + { + object[] gpuParameters = + marshaller.ConvertParameters( + buffers, + copyBack, + parameters + ); + // CUDA's parameterless wrapper has one unused argument. + if (gpuParameters.Length == 0 && accelerator.AcceleratorType == AcceleratorType.Cuda && + compiled.NumParameters == 1) + gpuParameters = new object[] { 0 }; + + compiled.Launch(accelerator.DefaultStream, config, gpuParameters); + accelerator.Synchronize(); + foreach (var copy in copyBack) + copy(); + } + finally + { + try + { + accelerator.Synchronize(); + } + finally + { + foreach (var buffer in buffers) + buffer.Dispose(); + } + } } private static int GetBlockCount(int length, int groupSize, int gridLimit, string parameterName) @@ -129,6 +136,21 @@ private static int GetBlockCount(int length, int groupSize, int gridLimit, strin private static int DivideRoundUp(int length, int divisor) => (int)((length + (long)divisor - 1) / divisor); + private void ValidateCpuLaunchSize(KernelConfig config) + { + if (accelerator.AcceleratorType != AcceleratorType.CPU || !config.IsValid) + return; + + long width = (long)config.GridDim.X * config.GroupDim.X; + long height = (long)config.GridDim.Y * config.GroupDim.Y; + long depth = (long)config.GridDim.Z * config.GroupDim.Z; + + // ILGPU's CPU launcher flattens the padded extent into a 32-bit index. + if (width > int.MaxValue / height || width * height > int.MaxValue / depth) + throw new ArgumentOutOfRangeException(nameof(config), + "A CPU launch cannot exceed Int32.MaxValue threads after rounding to whole groups."); + } + private static void ValidateArguments(Delegate kernel, object[] parameters) { ArgumentNullException.ThrowIfNull(parameters); @@ -138,29 +160,5 @@ private static void ValidateArguments(Delegate kernel, object[] parameters) $"Kernel expects {expected} parameters, but {parameters.Length} were provided.", nameof(parameters)); } - - private object[] GetLaunchArguments(ILGPU.Runtime.Kernel compiled, object[] arguments) - { - // CUDA's parameterless wrapper has one unused argument. - if (accelerator.AcceleratorType == AcceleratorType.Cuda && - arguments.Length == 0 && compiled.NumParameters == 1) - return new object[] { 0 }; - - return arguments; - } - - public void ExecuteOnDevice( - Delegate kernel, - KernelConfig config) - { - object[] parameters = Array.Empty(); - ValidateArguments(kernel, parameters); - var compiled = compiler.GetOrCompile(kernel); - compiled.Launch( - accelerator.DefaultStream, - config, - GetLaunchArguments(compiled, parameters) - ); - } } -} \ No newline at end of file +} diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index e024fa9..058874b 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -95,12 +95,6 @@ internal void Execute2D( { executor.Execute2D(kernel, width, height, parameters); } - internal void ExecuteOnDevice( - Delegate kernel, - KernelConfig config) - { - executor.ExecuteOnDevice(kernel, config); - } public object[] ConvertParameters( List buffers, List copyBack, diff --git a/Kernelium/Memory/ParameterMarshaller.cs b/Kernelium/Memory/ParameterMarshaller.cs index c890724..5dbdf9a 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -1,12 +1,14 @@ using ILGPU; using ILGPU.Runtime; using System.Reflection; +using System.Runtime.CompilerServices; namespace Kernelium.Memory { internal sealed class ParameterMarshaller { private readonly Accelerator accelerator; + private static readonly ConditionalWeakTable viewFields = new(); private static readonly MethodInfo marshalArrayMethod = typeof(ParameterMarshaller).GetMethod( @@ -35,46 +37,63 @@ public object[] ConvertParameters( if (parameter is IGPUBuffer gpuBuffer) parameter = gpuBuffer.GetView(); - if (parameter is IArrayView { Buffer: { } backingBuffer }) - { - ObjectDisposedException.ThrowIf(backingBuffer.IsDisposed, backingBuffer); - if (!ReferenceEquals(backingBuffer.Accelerator, accelerator)) - throw new ArgumentException( - $"Kernel parameter {i} belongs to a different accelerator.", - nameof(parameters)); - } var arrayArgument = parameter as ArrayArgument; - if ((arrayArgument?.Data ?? parameter) is Array array) - { - Type type = array.GetType().GetElementType()!; - - if (array.GetType() != type.MakeArrayType()) - throw new NotSupportedException( - "Only one-dimensional arrays are supported." - ); - - bool copyIn = arrayArgument is null || arrayArgument.IsInput; - bool copyOut = arrayArgument is null || !arrayArgument.IsInput; - result[i] = marshalArrayMethod - .MakeGenericMethod(type) - .Invoke(this, new object[] - { - buffers, - copyBack, - array, - copyIn, - copyOut - })!; - } - else + if ((arrayArgument?.Data ?? parameter) is not Array array) { + ValidateViews(parameter, i); result[i] = parameter; + continue; } + + Type elementType = array.GetType().GetElementType()!; + if (array.GetType() != elementType.MakeArrayType()) + throw new NotSupportedException("Only one-dimensional arrays are supported."); + + bool copyIn = arrayArgument is null || arrayArgument.IsInput; + bool copyOut = arrayArgument is null || !arrayArgument.IsInput; + result[i] = marshalArrayMethod + .MakeGenericMethod(elementType) + .Invoke(this, new object[] { buffers, copyBack, array, copyIn, copyOut })!; } return result; } + private void ValidateViews(object value, int parameterIndex) + { + if (value is IArrayView view) + { + if (view.Buffer is not { } buffer) + return; + + ObjectDisposedException.ThrowIf(buffer.IsDisposed, buffer); + if (!ReferenceEquals(buffer.Accelerator, accelerator)) + throw new ArgumentException( + $"Kernel parameter {parameterIndex} contains a view from a different accelerator.", + "parameters"); + return; + } + + Type type = value.GetType(); + if (!MayContainView(type)) + return; + + var fields = viewFields.GetValue(type, static type => + type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(field => MayContainView(field.FieldType)) + .ToArray()); + + foreach (var field in fields) + { + if (field.GetValue(value) is { } fieldValue) + ValidateViews(fieldValue, parameterIndex); + } + } + + private static bool MayContainView(Type type) => + typeof(IArrayView).IsAssignableFrom(type) || + (type.IsValueType && !type.IsPrimitive && !type.IsEnum); + private ArrayView MarshalArray( List buffers, List copyBack, From 6bc6572f9bf84482e66a2d0ac01e8d9ab9801f05 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 14:08:29 +0100 Subject: [PATCH 8/9] Document benchmark results --- README.md | 2 + benchmarks/results/2026-11-28.md | 76 ++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 benchmarks/results/2026-11-28.md diff --git a/README.md b/README.md index e5024df..2250933 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ Use `DeviceIndex` to select a device when requesting an explicit backend. For coding agents generating an integration, the [NuGet readme](https://www.nuget.org/packages/Kernelium#readme) includes the complete quickstart. The package also ships `llms.txt`, a compact reference to the same APIs and resource rules. +See the [benchmark results](benchmarks/results/2026-11-28.md) for measurements against native C# and raw ILGPU on a Ryzen 7 5700G and RTX 4060 Ti. + ## API Documentation ### GPU diff --git a/benchmarks/results/2026-11-28.md b/benchmarks/results/2026-11-28.md new file mode 100644 index 0000000..585ebfe --- /dev/null +++ b/benchmarks/results/2026-11-28.md @@ -0,0 +1,76 @@ +# Benchmark results — 2026-11-28 + +These BenchmarkDotNet measurements compare Kernelium with raw ILGPU and native C# for vector addition and Mandelbrot workloads at 256², 1024², and 4096². Timings are means from repeated benchmark iterations. The full generated report is included below. + +## Highlights + +- **Mandelbrot on CUDA scales well:** at 4096², Kernelium took 12.15 ms, versus 366 ms for C# using native threads and 1,862 ms for single-threaded C# (about 30× and 153× faster, respectively). +- **Vector addition is transfer-sensitive:** at 4096², Kernelium CUDA took 12.27 ms, close to single-threaded C# at 12.93 ms and slower than native-threaded C# at 10.62 ms. +- **Kernelium CUDA is close to raw ILGPU:** at 4096², raw ILGPU took 11.26 ms for vector addition and 12.10 ms for Mandelbrot. +- **The ILGPU CPU accelerator is slow for these cases:** at 4096², Kernelium CPU took 6.10 s for vector addition and 7.82 s for Mandelbrot; raw ILGPU was in the same range. +- **OpenCL was not measured in this run.** + +## Test environment and scope + +- Windows 11, .NET 10.0.15, BenchmarkDotNet 0.15.8 +- AMD Ryzen 7 5700G (8 physical / 16 logical cores) +- NVIDIA GeForce RTX 4060 Ti +- 36 benchmark cases covering two workloads, three square sizes, and the available C#, Kernelium CPU/CUDA, and raw ILGPU CPU/CUDA implementations + +These numbers describe this machine and these benchmark implementations. Device buffers and input uploads are prepared outside the timed region; each timed GPU operation includes kernel execution, synchronization, and output download. The measurements therefore include readback cost and are not pure device-kernel throughput. + +## Full BenchmarkDotNet report + +``` + +BenchmarkDotNet v0.15.8, Windows 11 (10.0.26300.10075) +AMD Ryzen 7 5700G with Radeon Graphics 3.80GHz, 1 CPU, 16 logical and 8 physical cores +.NET SDK 10.0.404 + [Host] : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v3 + DefaultJob : .NET 10.0.15 (10.0.15, 10.0.1526.53008), X64 RyuJIT x86-64-v3 + + +``` +| Method | Side | Workload | Mean | Error | StdDev | Ratio | RatioSD | Allocated | Alloc Ratio | +|-------------------- |----- |----------- |----------------:|--------------:|--------------:|-------:|--------:|----------:|------------:| +| **CSharpSingleThread** | **256** | **VectorAdd** | **43.93 μs** | **0.116 μs** | **0.108 μs** | **1.00** | **0.00** | **-** | **NA** | +| CSharpNativeThreads | 256 | VectorAdd | 184.24 μs | 2.285 μs | 2.025 μs | 4.19 | 0.05 | - | NA | +| KerneliumCpu | 256 | VectorAdd | 24,335.26 μs | 73.200 μs | 61.125 μs | 553.94 | 1.88 | 672 B | NA | +| KerneliumCuda | 256 | VectorAdd | 92.76 μs | 0.512 μs | 0.479 μs | 2.11 | 0.01 | 576 B | NA | +| RawIlgpuCpu | 256 | VectorAdd | 24,209.11 μs | 148.434 μs | 138.846 μs | 551.06 | 3.33 | 224 B | NA | +| RawIlgpuCuda | 256 | VectorAdd | 89.67 μs | 0.257 μs | 0.215 μs | 2.04 | 0.01 | 128 B | NA | +| | | | | | | | | | | +| **CSharpSingleThread** | **256** | **Mandelbrot** | **7,358.86 μs** | **3.628 μs** | **3.216 μs** | **1.00** | **0.00** | **-** | **NA** | +| CSharpNativeThreads | 256 | Mandelbrot | 1,730.83 μs | 8.817 μs | 7.816 μs | 0.24 | 0.00 | - | NA | +| KerneliumCpu | 256 | Mandelbrot | 30,781.64 μs | 46.016 μs | 43.044 μs | 4.18 | 0.01 | 536 B | NA | +| KerneliumCuda | 256 | Mandelbrot | 118.06 μs | 0.114 μs | 0.101 μs | 0.02 | 0.00 | 488 B | NA | +| RawIlgpuCpu | 256 | Mandelbrot | 30,923.93 μs | 219.908 μs | 205.702 μs | 4.20 | 0.03 | 689 B | NA | +| RawIlgpuCuda | 256 | Mandelbrot | 115.57 μs | 0.279 μs | 0.261 μs | 0.02 | 0.00 | 128 B | NA | +| | | | | | | | | | | +| **CSharpSingleThread** | **1024** | **VectorAdd** | **702.59 μs** | **2.515 μs** | **2.229 μs** | **1.00** | **0.00** | **-** | **NA** | +| CSharpNativeThreads | 1024 | VectorAdd | 310.25 μs | 2.524 μs | 2.361 μs | 0.44 | 0.00 | - | NA | +| KerneliumCpu | 1024 | VectorAdd | 379,326.23 μs | 5,686.950 μs | 5,319.577 μs | 539.90 | 7.52 | 672 B | NA | +| KerneliumCuda | 1024 | VectorAdd | 802.58 μs | 0.985 μs | 0.823 μs | 1.14 | 0.00 | 528 B | NA | +| RawIlgpuCpu | 1024 | VectorAdd | 397,255.80 μs | 4,130.953 μs | 3,864.096 μs | 565.42 | 5.60 | 224 B | NA | +| RawIlgpuCuda | 1024 | VectorAdd | 799.50 μs | 1.336 μs | 1.184 μs | 1.14 | 0.00 | 112 B | NA | +| | | | | | | | | | | +| **CSharpSingleThread** | **1024** | **Mandelbrot** | **118,544.58 μs** | **543.711 μs** | **508.587 μs** | **1.000** | **0.01** | **-** | **NA** | +| CSharpNativeThreads | 1024 | Mandelbrot | 22,701.90 μs | 221.850 μs | 207.519 μs | 0.192 | 0.00 | - | NA | +| KerneliumCpu | 1024 | Mandelbrot | 488,938.67 μs | 2,989.305 μs | 2,649.941 μs | 4.125 | 0.03 | 536 B | NA | +| KerneliumCuda | 1024 | Mandelbrot | 920.86 μs | 0.556 μs | 0.464 μs | 0.008 | 0.00 | 472 B | NA | +| RawIlgpuCpu | 1024 | Mandelbrot | 485,543.50 μs | 4,226.696 μs | 3,953.654 μs | 4.096 | 0.04 | 176 B | NA | +| RawIlgpuCuda | 1024 | Mandelbrot | 917.05 μs | 2.141 μs | 2.003 μs | 0.008 | 0.00 | 112 B | NA | +| | | | | | | | | | | +| **CSharpSingleThread** | **4096** | **VectorAdd** | **12,926.89 μs** | **79.759 μs** | **74.606 μs** | **1.00** | **0.01** | **-** | **NA** | +| CSharpNativeThreads | 4096 | VectorAdd | 10,622.31 μs | 41.977 μs | 39.265 μs | 0.82 | 0.01 | - | NA | +| KerneliumCpu | 4096 | VectorAdd | 6,103,064.75 μs | 25,386.776 μs | 21,199.107 μs | 472.14 | 3.08 | 672 B | NA | +| KerneliumCuda | 4096 | VectorAdd | 12,268.57 μs | 240.423 μs | 236.127 μs | 0.95 | 0.02 | 528 B | NA | +| RawIlgpuCpu | 4096 | VectorAdd | 6,046,217.83 μs | 14,643.413 μs | 11,432.613 μs | 467.74 | 2.75 | 224 B | NA | +| RawIlgpuCuda | 4096 | VectorAdd | 11,262.13 μs | 4.813 μs | 4.266 μs | 0.87 | 0.00 | 80 B | NA | +| | | | | | | | | | | +| **CSharpSingleThread** | **4096** | **Mandelbrot** | **1,862,285.55 μs** | **2,528.853 μs** | **2,365.490 μs** | **1.000** | **0.00** | **-** | **NA** | +| CSharpNativeThreads | 4096 | Mandelbrot | 366,304.24 μs | 6,678.613 μs | 6,559.291 μs | 0.197 | 0.00 | - | NA | +| KerneliumCpu | 4096 | Mandelbrot | 7,817,549.57 μs | 65,845.009 μs | 61,591.463 μs | 4.198 | 0.03 | 536 B | NA | +| KerneliumCuda | 4096 | Mandelbrot | 12,150.44 μs | 18.062 μs | 16.895 μs | 0.007 | 0.00 | 440 B | NA | +| RawIlgpuCpu | 4096 | Mandelbrot | 7,933,003.88 μs | 33,490.785 μs | 27,966.322 μs | 4.260 | 0.02 | 176 B | NA | +| RawIlgpuCuda | 4096 | Mandelbrot | 12,103.77 μs | 8.284 μs | 7.344 μs | 0.006 | 0.00 | 80 B | NA | From 0ef05f958ad0456c8cc711c644955b1c239c988b Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Sat, 28 Nov 2026 14:14:54 +0100 Subject: [PATCH 9/9] Prepare 0.2.0 preview release --- .github/workflows/nuget.yml | 2 +- Kernelium/Kernelium.csproj | 2 +- README.md | 2 +- llms.txt | 3 +-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index a6c58ee..ad37c1a 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -27,7 +27,7 @@ jobs: run: | version="${TAG#v}" if [[ ! "$version" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then - echo "::error::Expected a release tag such as v0.1.0-preview.1 or v0.1.0." + echo "::error::Expected a release tag such as v0.2.0-preview.1 or v0.2.0." exit 1 fi echo "package=$version" >> "$GITHUB_OUTPUT" diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index b71550a..5729eca 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -6,7 +6,7 @@ enable true Kernelium - 0.1.0-preview.1 + 0.2.0-preview.1 Raphael Hinterdorfer GPU computing for C# and .NET 10. Compile and launch ILGPU kernels on CUDA, OpenCL, or CPU with automatic array transfers and reusable device buffers. gpu gpu-computing gpu-acceleration gpgpu csharp dotnet ilgpu cuda opencl parallel-computing diff --git a/README.md b/README.md index 2250933..64b378e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ Kernelium is in preview and is MIT licensed. The package targets .NET 10. ## Install ```sh -dotnet add package Kernelium --version 0.1.0-preview.1 +dotnet add package Kernelium --version 0.2.0-preview.1 ``` ## Quickstart diff --git a/llms.txt b/llms.txt index 32ff801..fa96aec 100644 --- a/llms.txt +++ b/llms.txt @@ -4,8 +4,7 @@ ## Install and check the version -- `dotnet add package Kernelium --version 0.1.0-preview.1` installs the first public preview. -- The quickstart and reusable buffers below work with that preview. `ArrayArgument.Input`, `ArrayArgument.Output`, `Execute2D`, `GPU.Device`, and `GPU.Accelerator` were added after `0.1.0-preview.1`. Check the referenced package version before using them. +- `dotnet add package Kernelium --version 0.2.0-preview.1` installs the current preview with the APIs documented below. ## Quickstart