From 8371fff2f0c677c60bb91e76588097792816fcb8 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 18:52:27 +0100 Subject: [PATCH 01/11] Prepare Kernelium 1.0.0 release --- Kernelium.Test/AsyncKernelExecution.cs | 60 +++--- Kernelium.Test/DeviceOperationsTests.cs | 2 +- Kernelium.Test/GPUBufferTests.cs | 12 +- Kernelium.Test/GPUInit.cs | 10 +- Kernelium.Test/KernelExecution.cs | 90 ++++---- Kernelium.Test/StreamWorkTests.cs | 6 +- Kernelium.Test/TypedKernelTests.cs | 234 +++++++++++++++++++++ Kernelium/Compilation/KernelCompiler.cs | 10 + Kernelium/DataTypes/BufferTransferInfo.cs | 13 ++ Kernelium/DataTypes/GPUConfiguration.cs | 29 ++- Kernelium/DataTypes/KernelExecutionInfo.cs | 45 ++++ Kernelium/Enums/CompilationStrategy.cs | 21 +- Kernelium/Enums/ComputeBackend.cs | 10 + Kernelium/Enums/HardwareType.cs | 1 + Kernelium/Execution/CudaStaging.cs | 2 +- Kernelium/Execution/DeviceOperations.cs | 64 +++++- Kernelium/Execution/KernelExecutor.cs | 100 +++++++-- Kernelium/Execution/StreamWork.cs | 11 + Kernelium/GPU.cs | 117 ++++++++--- Kernelium/Kernel.cs | 24 ++- Kernelium/KernelArgument.cs | 44 ++++ Kernelium/Kernelium.csproj | 3 +- Kernelium/Memory/GPUBuffer.cs | 20 +- Kernelium/TypedKernel.cs | 213 +++++++++++++++++++ Kernelium/TypedKernelExtensions.cs | 55 +++++ README.md | 163 +++++++++++--- llms.txt | 28 ++- 27 files changed, 1175 insertions(+), 212 deletions(-) create mode 100644 Kernelium.Test/TypedKernelTests.cs create mode 100644 Kernelium/DataTypes/BufferTransferInfo.cs create mode 100644 Kernelium/DataTypes/KernelExecutionInfo.cs create mode 100644 Kernelium/Enums/ComputeBackend.cs create mode 100644 Kernelium/KernelArgument.cs create mode 100644 Kernelium/TypedKernel.cs create mode 100644 Kernelium/TypedKernelExtensions.cs diff --git a/Kernelium.Test/AsyncKernelExecution.cs b/Kernelium.Test/AsyncKernelExecution.cs index 4c7041d..b61b4c9 100644 --- a/Kernelium.Test/AsyncKernelExecution.cs +++ b/Kernelium.Test/AsyncKernelExecution.cs @@ -12,8 +12,8 @@ public static class AsyncKernelExecution public static async Task OneDimensionalAndExplicitLaunchesCopyBackBeforeCompletion() { using var gpu = CreateCpu(); - var copy = gpu.GenerateKernel(CopyAndClear); - var increment = gpu.GenerateKernel(TestHelper.Increment, precompile: false); + var copy = gpu.CreateKernel(CopyAndClear); + var increment = gpu.CreateKernel(TestHelper.Increment, precompile: false); int[] source = [2, 3, 4]; int[] output = new int[source.Length]; int[] readWrite = [5, 6, 7]; @@ -31,7 +31,7 @@ await Task.WhenAll( public static async Task TwoDimensionalLaunchCopiesEveryCoordinate() { using var gpu = CreateCpu(); - var kernel = gpu.GenerateKernel(WritePixel); + var kernel = gpu.CreateKernel(WritePixel); const int width = 19; const int height = 17; var output = new int[width * height]; @@ -45,7 +45,7 @@ public static async Task TwoDimensionalLaunchCopiesEveryCoordinate() public static async Task DuplicateHostArgumentsUseSeparateDeviceAllocations() { using var gpu = CreateCpu(); - var kernel = gpu.GenerateKernel(ClearThenCopy); + var kernel = gpu.CreateKernel(ClearThenCopy); int[] data = [3, 4]; await kernel.ExecuteAsync(data.Length, ArrayArgument.Input(data), data, ArrayArgument.Output(data)); @@ -58,8 +58,8 @@ public static async Task CapturesParameterEntriesAndOrdersHostWritesAcrossGpuIns { using var firstGpu = CreateCpu(); using var secondGpu = CreateCpu(); - var square = firstGpu.GenerateKernel(TestHelper.Square); - var increment = secondGpu.GenerateKernel(TestHelper.Increment); + var square = firstGpu.CreateKernel(TestHelper.Square); + var increment = secondGpu.CreateKernel(TestHelper.Increment); int[] data = [2, 3]; int[] replacement = [8, 9]; object[] parameters = [data]; @@ -85,9 +85,9 @@ public static async Task BufferAliasesAndDefaultStreamTransfersUseSubmissionOrde { using var gpu = CreateCpu(); using var buffer = gpu.Upload(new[] { 1, 2, 3, 4 }); - var increment = gpu.GenerateKernel(TestHelper.Increment); - var square = gpu.GenerateKernel(TestHelper.Square); - var nested = gpu.GenerateKernel(IncrementNested); + var increment = gpu.CreateKernel(TestHelper.Increment); + var square = gpu.CreateKernel(TestHelper.Square); + var nested = gpu.CreateKernel(IncrementNested); var first = increment.ExecuteAsync(4, buffer); var second = nested.ExecuteAsync(2, new NestedView(buffer.View.SubView(1, 2))); @@ -106,7 +106,7 @@ public static async Task BufferAliasesAndDefaultStreamTransfersUseSubmissionOrde public static async Task ConcurrentHostSubmissionsCompleteOnOneCpuAccelerator() { using var gpu = CreateCpu(); - var increment = gpu.GenerateKernel(TestHelper.Increment, precompile: false); + var increment = gpu.CreateKernel(TestHelper.Increment, precompile: false); int[] shared = new int[13]; var independent = Enumerable.Range(0, 16).Select(value => new[] { value }).ToArray(); var submissions = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -126,7 +126,7 @@ public static async Task ConcurrentHostSubmissionsCompleteOnOneCpuAccelerator() public static async Task AsyncFailureFaultsItsTaskAndLaterConflictCanProceed() { using var gpu = CreateCpu(); - var increment = gpu.GenerateKernel(TestHelper.Increment); + var increment = gpu.CreateKernel(TestHelper.Increment); int[] data = [4]; var oversized = new KernelConfig(new Index3D(1_024, 1_024, 4_096), new Index3D(1, 1, 1)); Task invalid = increment.ExecuteAsync(oversized, data); @@ -144,7 +144,7 @@ public static async Task BufferDisposalWaitsForAcceptedViewUses() { using var gpu = CreateCpu(); using var buffer = gpu.Upload(new[] { 11 }); - var copy = gpu.GenerateKernel(TestHelper.Copy); + var copy = gpu.CreateKernel(TestHelper.Copy); var alias = buffer.View.SubView(0, 1); var allocation = OperationScheduler.For(buffer.Allocation); int[] output = new int[1]; @@ -173,7 +173,7 @@ public static async Task GpuDisposalDrainsQueuedWork() { using var gpu = CreateCpu(); using var buffer = gpu.Upload(new[] { 13 }); - var copy = gpu.GenerateKernel(TestHelper.Copy); + var copy = gpu.CreateKernel(TestHelper.Copy); int[] output = new int[1]; Task pending; Task dispose; @@ -195,19 +195,19 @@ public static async Task GpuDisposalDrainsQueuedWork() Assert.That(output[0], Is.EqualTo(13)); } - [TestCase(HardwareType.Cuda, AcceleratorType.Cuda)] - [TestCase(HardwareType.OpenCL, AcceleratorType.OpenCL)] - public static async Task AsyncStreamsAndDefaultStreamInterop(HardwareType hardware, AcceleratorType accelerator) + [TestCase(ComputeBackend.Cuda, AcceleratorType.Cuda)] + [TestCase(ComputeBackend.OpenCL, AcceleratorType.OpenCL)] + public static async Task AsyncStreamsAndDefaultStreamInterop(ComputeBackend hardware, AcceleratorType accelerator) { using var context = Context.CreateDefault(); if (!context.Devices.Any(device => device.AcceleratorType == accelerator)) Assert.Ignore($"{accelerator} accelerator unavailable."); - using var gpu = new GPU(new() { HardwareType = hardware }); + using var gpu = new GPU(new() { ComputeBackend = hardware }); using var buffer = gpu.Upload(new[] { 3, 4 }); var raw = gpu.Accelerator.LoadStreamKernel>(TestHelper.Increment); - var square = gpu.GenerateKernel(TestHelper.Square); - var increment = gpu.GenerateKernel(TestHelper.Increment); + var square = gpu.CreateKernel(TestHelper.Square); + var increment = gpu.CreateKernel(TestHelper.Increment); int[] first = [5, 6]; int[] second = [7, 8]; @@ -228,7 +228,7 @@ public static void CudaBufferTransfersReuseStagingAcrossSizesAndTypes() if (!context.Devices.Any(device => device.AcceleratorType == AcceleratorType.Cuda)) Assert.Ignore("CUDA accelerator unavailable."); - using var gpu = new GPU(new() { HardwareType = HardwareType.Cuda }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cuda }); using var small = gpu.Allocate(3); using var large = gpu.Allocate(4); @@ -241,15 +241,21 @@ public static void CudaBufferTransfersReuseStagingAcrossSizesAndTypes() Assert.That(large.Download(), Is.EqualTo(new long[] { 10, 20, 30, 40 })); } - [Test] - public static async Task CudaHostArrayLaunchesPreserveAliasedArgumentsAcrossRepeatedSubmissions() + [TestCase(0L)] + [TestCase(240L)] // Each stream can cache one of the three 68-byte arguments. + [TestCase(384L * 1024 * 1024)] + public static async Task CudaHostArrayLaunchesPreserveAliasedArgumentsAcrossRepeatedSubmissions(long cacheBytes) { using var context = Context.CreateDefault(); if (!context.Devices.Any(device => device.AcceleratorType == AcceleratorType.Cuda)) Assert.Ignore("CUDA accelerator unavailable."); - using var gpu = new GPU(new() { HardwareType = HardwareType.Cuda }); - var copy = gpu.GenerateKernel(ClearThenCopy); + using var gpu = new GPU(new() + { + ComputeBackend = ComputeBackend.Cuda, + CudaPinnedStagingCacheBytes = cacheBytes + }); + var copy = gpu.CreateKernel(ClearThenCopy); for (int length = 17; length >= 1; length -= 8) { int[] expected = Enumerable.Range(1, length).ToArray(); @@ -275,7 +281,7 @@ public static void CudaStagingCacheEnforcesBudgetAndReusesExistingRegions() if (!context.Devices.Any(device => device.AcceleratorType == AcceleratorType.Cuda)) Assert.Ignore("CUDA accelerator unavailable."); - using var gpu = new GPU(new() { HardwareType = HardwareType.Cuda }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cuda }); var pool = new CudaStagingPool(gpu.Accelerator, byteBudget: 64); var first = pool.TryRent(0, 32); var second = pool.TryRent(1, 16); @@ -294,7 +300,7 @@ public static async Task LaunchesAcceptCovariantParamsArraysWithoutReplacingCall { using var gpu = CreateCpu(); using var buffer = gpu.Upload(new[] { 4 }); - var increment = gpu.GenerateKernel(TestHelper.Increment); + var increment = gpu.CreateKernel(TestHelper.Increment); var bufferParameters = new[] { buffer }; int[] data = [7]; int[][] hostParameters = [data]; @@ -308,7 +314,7 @@ public static async Task LaunchesAcceptCovariantParamsArraysWithoutReplacingCall Assert.That(data, Is.EqualTo(new[] { 8 })); } - private static GPU CreateCpu() => new(new() { HardwareType = HardwareType.Cpu }); + private static GPU CreateCpu() => new(new() { ComputeBackend = ComputeBackend.Cpu }); private static OperationScheduler.Reservation Hold(int[] data) { diff --git a/Kernelium.Test/DeviceOperationsTests.cs b/Kernelium.Test/DeviceOperationsTests.cs index aebe2d0..91d316b 100644 --- a/Kernelium.Test/DeviceOperationsTests.cs +++ b/Kernelium.Test/DeviceOperationsTests.cs @@ -9,7 +9,7 @@ internal static class DeviceOperationsTests [Test] public static void AsyncCpuWorkRejectsAnUnsafeDefaultStream() { - using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); var operations = new DeviceOperations(gpu.Accelerator); var defaultStream = operations.GetClaims(useDefaultStream: true).TakeAccess() .Single(claim => claim.Value).Key; diff --git a/Kernelium.Test/GPUBufferTests.cs b/Kernelium.Test/GPUBufferTests.cs index 2e1c6b2..e707469 100644 --- a/Kernelium.Test/GPUBufferTests.cs +++ b/Kernelium.Test/GPUBufferTests.cs @@ -6,7 +6,7 @@ namespace Kernelium.Test [TestFixture] public static class GPUBufferTests { - private static GPU CreateGpu() => new(new() { HardwareType = HardwareType.Cpu }); + private static GPU CreateGpu() => new(new() { ComputeBackend = ComputeBackend.Cpu }); [Test] public static void AllocateReturnsZeroedBufferOfRequestedLength() @@ -78,8 +78,8 @@ public static void TransfersRejectNullArrays() public static void BufferPersistsAcrossKernelExecutions() { using var gpu = CreateGpu(); - var increment = gpu.GenerateKernel(TestHelper.Increment); - var copy = gpu.GenerateKernel(TestHelper.Copy); + var increment = gpu.CreateKernel(TestHelper.Increment); + var copy = gpu.CreateKernel(TestHelper.Copy); int[] source = { 1, 2, 3 }; using var buffer = gpu.Upload(source); var destination = new int[source.Length]; @@ -123,7 +123,7 @@ public static void KernelRejectsDisposedBufferAndPreviouslyObtainedView() using var gpu = CreateGpu(); using var buffer = gpu.Allocate(1); var view = buffer.View; - var kernel = gpu.GenerateKernel(TestHelper.Increment); + var kernel = gpu.CreateKernel(TestHelper.Increment); buffer.Dispose(); Assert.That(((IArrayView)buffer.NativeView).Buffer, Is.SameAs(((IArrayView)view).Buffer)); @@ -141,7 +141,7 @@ public static void KernelRejectsBufferFromDifferentAccelerator(bool useView) using var gpu = CreateGpu(); using var otherGpu = CreateGpu(); using var buffer = otherGpu.Upload(new[] { 1 }); - var kernel = gpu.GenerateKernel(TestHelper.Increment); + var kernel = gpu.CreateKernel(TestHelper.Increment); Assert.Throws(() => kernel.Execute(new KernelConfig(1, 1), useView ? (object)buffer.View : buffer)); @@ -155,7 +155,7 @@ public static void KernelValidatesNestedViewOwnership() using var otherGpu = CreateGpu(); using var local = gpu.Upload(new[] { 3 }); using var foreign = otherGpu.Upload(new[] { 7 }); - var kernel = gpu.GenerateKernel(IncrementNestedView); + var kernel = gpu.CreateKernel(IncrementNestedView); var argument = new NestedView(new BufferView(local.View)); kernel.Execute(1, argument); diff --git a/Kernelium.Test/GPUInit.cs b/Kernelium.Test/GPUInit.cs index 6b6f1ea..2befabb 100644 --- a/Kernelium.Test/GPUInit.cs +++ b/Kernelium.Test/GPUInit.cs @@ -14,14 +14,14 @@ public static void TryInit() using var gpu = new GPU(new() { DeviceIndex = 0, - HardwareType = Enums.HardwareType.Auto + ComputeBackend = Enums.ComputeBackend.Auto }); }); } [Test] public static void UseSelectedAcceleratorWithKernelium() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); var accelerator = gpu.Accelerator; Assert.That(gpu.Device, Is.SameAs(accelerator.Device)); @@ -30,7 +30,7 @@ public static void UseSelectedAcceleratorWithKernelium() Assert.That(gpu.Device.MaxNumThreadsPerGroup, Is.Positive); using var buffer = accelerator.Allocate1D(4); - var kernel = gpu.GenerateKernel(TestHelper.Fill); + var kernel = gpu.CreateKernel(TestHelper.Fill); kernel.Execute(4, (ArrayView)buffer.View, 42); Assert.That(buffer.GetAsArray1D(), Is.All.EqualTo(42)); @@ -44,10 +44,10 @@ public static void TryInitKernel() using var gpu = new GPU(new() { DeviceIndex = 0, - HardwareType = Enums.HardwareType.Auto + ComputeBackend = Enums.ComputeBackend.Auto }); - var kernel = gpu.GenerateKernel(TestHelper.TestKernel); + var kernel = gpu.CreateKernel(TestHelper.TestKernel); kernel.Compile(); }); } diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index 2b84c35..5206670 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -12,7 +12,7 @@ public static void ExecuteKernel() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.TestKernelWithPrimitiveValue); Assert.DoesNotThrow(() => @@ -22,38 +22,38 @@ public static void ExecuteKernel() [Test] public static void BothKernelEntryPointsRejectMulticastDelegates() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); Action> kernel = TestHelper.Increment; kernel += TestHelper.Square; Assert.Throws(() => new Kernel(gpu, kernel)); - Assert.Throws(() => gpu.GenerateKernel(kernel)); + Assert.Throws(() => gpu.CreateKernel(kernel)); } [Test] public static void ExecuteKernelWithoutParameters() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.NoParameters); Assert.DoesNotThrow(() => kernel.Execute(new KernelConfig(1, 1))); } - [TestCase(Enums.HardwareType.Cuda, AcceleratorType.Cuda)] - [TestCase(Enums.HardwareType.OpenCL, AcceleratorType.OpenCL)] + [TestCase(Enums.ComputeBackend.Cuda, AcceleratorType.Cuda)] + [TestCase(Enums.ComputeBackend.OpenCL, AcceleratorType.OpenCL)] public static void ExecuteParameterlessKernelOnGpu( - Enums.HardwareType hardwareType, + Enums.ComputeBackend 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); + using var gpu = new GPU(new() { ComputeBackend = hardwareType }); + var kernel = gpu.CreateKernel(TestHelper.NoParameters); Assert.DoesNotThrow(() => kernel.Execute(1)); gpu.ClearKernelCache(); @@ -61,7 +61,7 @@ public static void ExecuteParameterlessKernelOnGpu( if (acceleratorType == AcceleratorType.OpenCL) { - var lambda = gpu.GenerateKernel((Action)(static () => { })); + var lambda = gpu.CreateKernel((Action)(static () => { })); Assert.DoesNotThrow(() => lambda.Execute(1)); } } @@ -69,8 +69,8 @@ public static void ExecuteParameterlessKernelOnGpu( [Test] public static void ExecuteParameterlessLambda() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); - var kernel = gpu.GenerateKernel((Action)(static () => { })); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel((Action)(static () => { })); Assert.DoesNotThrow(() => kernel.Execute(1)); } @@ -78,8 +78,8 @@ public static void ExecuteParameterlessLambda() [Test] public static void ExecuteRejectsNullArgumentList() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); - var kernel = gpu.GenerateKernel(TestHelper.NoParameters); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(TestHelper.NoParameters); var error = Assert.Throws(() => kernel.Execute(1, null!)); @@ -91,7 +91,7 @@ public static void ExecuteKernelWithArrayView() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel(TestHelper.TestKernel); + var kernel = gpu.CreateKernel(TestHelper.TestKernel); int[] data = new int[10]; @@ -104,8 +104,8 @@ public static void ExecuteKernelWithArrayView() [Test] public static void ExecuteWithInputAndOutputArrays() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); - var kernel = gpu.GenerateKernel(CopyThenClearInput); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(CopyThenClearInput); int[] input = [3, -4, 9]; int[] output = [-1, -1, -1]; @@ -130,8 +130,8 @@ private static void CopyThenClearInput(ArrayView input, ArrayView outp [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); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(DoublePixel); int[] input = Enumerable.Range(1, width * height).ToArray(); int[] output = new int[input.Length]; @@ -144,8 +144,8 @@ public static void Execute2DCoversEveryCoordinate(int width, int height) [Test] public static void CpuRejectsLaunchesWithTooManyPaddedThreads() { - using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu }); - var kernel = gpu.GenerateKernel(TestHelper.NoParameters); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(TestHelper.NoParameters); Assert.Throws(() => kernel.Execute2D(131_072, 32_768)); @@ -157,8 +157,8 @@ public static void CpuRejectsLaunchesWithTooManyPaddedThreads() [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); + using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(DoublePixel, precompile: false); var error = Assert.Throws(() => kernel.Execute2D(width, height)); @@ -186,7 +186,7 @@ public static void ExecuteWithDifferentArraySizes(int size) { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); int[] data = new int[size]; @@ -205,7 +205,7 @@ public static void ExecuteWithDifferentIntegerValues(int value) { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); int[] data = new int[32]; @@ -220,7 +220,7 @@ public static void ExecuteWithFloatArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); float[] data = new float[32]; @@ -235,7 +235,7 @@ public static void ExecuteWithDoubleArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); double[] data = new double[32]; @@ -250,7 +250,7 @@ public static void ExecuteWithLongArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); long[] data = new long[32]; @@ -265,7 +265,7 @@ public static void ExecuteWithByteArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); byte[] data = new byte[32]; @@ -280,7 +280,7 @@ public static void ExecuteSquareKernel() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel(TestHelper.Square); + var kernel = gpu.CreateKernel(TestHelper.Square); int[] data = { 1, 2, 3, 4, 5 }; @@ -297,7 +297,7 @@ public static void ExecuteWithScalarAndArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel(TestHelper.Multiply); + var kernel = gpu.CreateKernel(TestHelper.Multiply); float[] data = { 1, 2, 3, 4, 5 }; @@ -314,7 +314,7 @@ public static void ExecuteWithMultipleArrays() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel(TestHelper.Add); + var kernel = gpu.CreateKernel(TestHelper.Add); int[] a = { 1, 2, 3, 4 }; int[] b = { 10, 20, 30, 40 }; @@ -346,7 +346,7 @@ public static void ExecuteCopyKernel() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Copy); int[] source = { 10, 20, 30, 40 }; @@ -365,7 +365,7 @@ public static void ExecuteWithMixedParameters() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.MixedParameters); float[] data = { 1, 2, 3, 4 }; @@ -388,7 +388,7 @@ public static void ExecuteKernelMultipleTimes() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Increment); int[] data = new int[32]; @@ -404,7 +404,7 @@ public static void ExecuteKernelWithDifferentArrays() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); int[] a = new int[10]; @@ -428,9 +428,9 @@ public static void ExecuteMultipleKernels() { using var gpu = new GPU(); - var fill = gpu.GenerateKernel(TestHelper.Fill); - var square = gpu.GenerateKernel(TestHelper.Square); - var increment = gpu.GenerateKernel(TestHelper.Increment); + var fill = gpu.CreateKernel(TestHelper.Fill); + var square = gpu.CreateKernel(TestHelper.Square); + var increment = gpu.CreateKernel(TestHelper.Increment); int[] data = new int[32]; @@ -451,7 +451,7 @@ public static void ExecuteWithExplicitKernelConfig( { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.WriteIndex); int size = blocks * threads; @@ -475,7 +475,7 @@ public static void ExecuteWithUnevenWorkItemCount(int size) { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.WriteIndex); int[] data = new int[size]; @@ -493,7 +493,7 @@ public static void ExecuteWithInvalidWorkItemCount(int size) { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill); int[] data = new int[10]; @@ -507,7 +507,7 @@ public static void ExecuteWithoutPrecompilation() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.Fill, precompile: false); @@ -523,7 +523,7 @@ public static void ExecuteLargeArray() { using var gpu = new GPU(); - var kernel = gpu.GenerateKernel( + var kernel = gpu.CreateKernel( TestHelper.WriteIndex); const int size = 1_000_000; diff --git a/Kernelium.Test/StreamWorkTests.cs b/Kernelium.Test/StreamWorkTests.cs index 60da070..7c87197 100644 --- a/Kernelium.Test/StreamWorkTests.cs +++ b/Kernelium.Test/StreamWorkTests.cs @@ -11,7 +11,7 @@ internal static class StreamWorkTests [Test] public static void FailedStreamDrainRetainsResourcesAndPreventsReuse() { - using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); using var stream = new FailingStream(gpu.Accelerator); using var buffer = gpu.Allocate(1); var viewBeforeFailure = buffer.View; @@ -35,7 +35,7 @@ public static void FailedStreamDrainRetainsResourcesAndPreventsReuse() [Test] public static void ReportsOperationFailureAlongsideDrainFailure() { - using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); using var stream = new FailingStream(gpu.Accelerator); var work = new StreamWork(stream, new ConcurrentBag(), []); var operationError = new ArgumentException("Launch failed."); @@ -50,7 +50,7 @@ public static void ReportsOperationFailureAlongsideDrainFailure() [Test] public static void ReportsOperationFailureAlongsideCleanupFailure() { - using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); var work = new StreamWork(gpu.Accelerator.DefaultStream, new ConcurrentBag(), []); var operationError = new ArgumentException("Launch failed."); var cleanupError = new InvalidOperationException("Cleanup failed."); diff --git a/Kernelium.Test/TypedKernelTests.cs b/Kernelium.Test/TypedKernelTests.cs new file mode 100644 index 0000000..b8c9df0 --- /dev/null +++ b/Kernelium.Test/TypedKernelTests.cs @@ -0,0 +1,234 @@ +using System.Collections.Concurrent; +using ILGPU; +using Kernelium.DataTypes; +using Kernelium.Enums; + +namespace Kernelium.Test; + +internal static class TypedKernelTests +{ + [Test] + public static async Task TypedLaunchesAcceptScalarsAndArrayAdapters() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var kernel = gpu.CreateTypedKernel, ArrayView>(Add, precompile: false); + int[] input = [1, 2, 3]; + int[] result = new int[input.Length]; + + Assert.That(kernel.IsCompiled, Is.False); + await kernel.ExecuteAsync(result.Length, 4, KernelArgument.Input(input), KernelArgument.Output(result)); + Assert.That(kernel.IsCompiled, Is.True); + Assert.That(result, Is.EqualTo(new[] { 5, 6, 7 })); + + using var buffer = gpu.Upload(result); + kernel.Execute2D(result.Length, 1, 3, buffer.View, KernelArgument.ReadWrite(result)); + Assert.That(result, Is.EqualTo(new[] { 8, 9, 10 })); + + kernel.Execute(new KernelConfig(1, result.Length), -1, KernelArgument.Input(input), KernelArgument.Buffer(buffer)); + Assert.That(buffer.Download(), Is.EqualTo(new[] { 0, 1, 2 })); + } + + [Test] + public static async Task TypedDefaultUsesTheDefaultScalarValue() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var kernel = gpu.CreateTypedKernel, ArrayView>(Add); + int[] input = [1, 2, 3]; + int[] result = new int[input.Length]; + + await kernel.ExecuteAsync(result.Length, default, KernelArgument.Input(input), KernelArgument.Output(result)); + + Assert.That(result, Is.EqualTo(input)); + } + + [Test] + public static void InvalidTypedArgumentFaultsTheTaskAndReportsTheError() + { + KernelExecutionInfo? report = null; + using var gpu = new GPU(new() + { + ComputeBackend = ComputeBackend.Cpu, + ExecutionDiagnostics = info => report = info + }); + var kernel = gpu.CreateTypedKernel(UnusedReference, precompile: false); + + Task execution = kernel.ExecuteAsync(1, default); + var error = Assert.ThrowsAsync(() => execution); + + Assert.That(report?.Error, Is.SameAs(error)); + Assert.That(kernel.IsCompiled, Is.False); + } + + [Test] + public static async Task DiagnosticsReportLaunchesAndPreserveFailuresWhenTheCallbackThrows() + { + var reports = new ConcurrentQueue(); + using var gpu = new GPU(new() + { + ComputeBackend = ComputeBackend.Cpu, + ExecutionDiagnostics = info => + { + reports.Enqueue(info); + throw new InvalidOperationException("Observer failure."); + } + }); + var kernel = gpu.CreateKernel(Add, precompile: false); + int[] input = [1, 2, 3]; + int[] result = new int[input.Length]; + + await kernel.ExecuteAsync(result.Length, 4, ArrayArgument.Input(input), ArrayArgument.Output(result)); + var error = Assert.Throws(() => kernel.Execute(1, 4)); + + var zeroWork = Assert.ThrowsAsync(() => + kernel.ExecuteAsync(0, 4, ArrayArgument.Input(input), ArrayArgument.Output(result))); + var invalidHeight = Assert.Throws(() => + kernel.Execute2D(1, -1, 4, ArrayArgument.Input(input), ArrayArgument.Output(result))); + + var entries = reports.ToArray(); + Assert.That(entries, Has.Length.EqualTo(4)); + Assert.Multiple(() => + { + Assert.That(entries[0].Kernel, Is.EqualTo(kernel.Method.Method)); + Assert.That(entries[0].Backend, Is.EqualTo(ComputeBackend.Cpu)); + Assert.That(entries[0].DeviceName, Is.EqualTo(gpu.Device.Name)); + Assert.That(entries[0].IsAsync, Is.True); + Assert.That(entries[0].LaunchConfig, Is.Not.Null); + Assert.That(entries[0].Elapsed, Is.GreaterThanOrEqualTo(TimeSpan.Zero)); + Assert.That(entries[0].UploadBytes, Is.EqualTo(12L)); + Assert.That(entries[0].DownloadBytes, Is.EqualTo(12L)); + Assert.That(entries[0].Error, Is.Null); + Assert.That(entries[1].IsAsync, Is.False); + Assert.That(entries[1].LaunchConfig, Is.Null); + Assert.That(entries[1].Error, Is.SameAs(error)); + Assert.That(entries[2].IsAsync, Is.True); + Assert.That(entries[2].LaunchConfig, Is.Null); + Assert.That(entries[2].Error, Is.SameAs(zeroWork)); + Assert.That(entries[3].IsAsync, Is.False); + Assert.That(entries[3].LaunchConfig, Is.Null); + Assert.That(entries[3].Error, Is.SameAs(invalidHeight)); + Assert.That(result, Is.EqualTo(new[] { 5, 6, 7 })); + }); + } + + [Test] + public static async Task ExtentOverloadForwardsTheSameShapeToAFiveArgumentKernel() + { + KernelExecutionInfo? report = null; + using var gpu = new GPU(new() + { + ComputeBackend = ComputeBackend.Cpu, + ExecutionDiagnostics = info => report = info + }); + var method = Apply; + var kernel = gpu.CreateTypedKernel(method); + int[] input = [1, 2, 3, 4, 5, 6]; + int[] output = new int[input.Length]; + await kernel.Execute2DAsync(new Index2D(2, 3), 2, 1, + KernelArgument.Input(input), KernelArgument.Output(output)); + + Assert.That(output, Is.EqualTo(new[] { 3, 5, 7, 9, 11, 13 })); + Assert.That(report?.KernelName, Is.EqualTo(nameof(Apply))); + + static void Apply(Index2D extent, int multiplier, int offset, ArrayView input, ArrayView output) + { + var index = Grid.GlobalIndex.XY; + if (index.X < extent.X && index.Y < extent.Y) + { + int i = index.Y * extent.X + index.X; + output[i] = input[i] * multiplier + offset; + } + } + } + + [Test] + public static void ExplicitBufferTransfersReportBytesAndFailures() + { + var reports = new List(); + using var gpu = new GPU(new() + { + ComputeBackend = ComputeBackend.Cpu, + BufferTransferDiagnostics = info => + { + reports.Add(info); + throw new InvalidOperationException("Observer failure."); + } + }); + + using var buffer = gpu.Upload(new[] { 1, 2 }); + buffer.Upload([3, 4]); + Assert.That(buffer.Download(), Is.EqualTo(new[] { 3, 4 })); + int[] destination = new int[2]; + buffer.Download(destination); + Assert.That(destination, Is.EqualTo(new[] { 3, 4 })); + var error = Assert.Throws(() => buffer.Download(new int[1])); + + Assert.That(reports.Select(report => report.IsUpload), Is.EqualTo(new[] { true, true, false, false, false })); + Assert.That(reports.Select(report => report.Bytes), Is.EqualTo(new long[] { 8, 8, 8, 8, 4 })); + Assert.That(reports.Select(report => report.Backend), Is.All.EqualTo(ComputeBackend.Cpu)); + Assert.That(reports.Take(4).Select(report => report.Error), Is.All.Null); + Assert.That(reports[4].Error, Is.SameAs(error)); + } + + [Test] + public static async Task ManualCompilationUsesTheSharedCacheWithoutCompilingOnLaunch() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var method = Add; + var manual = gpu.CreateTypedKernel(method, CompilationStrategy.Manual); + int[] input = [2]; + int[] output = [0]; + + Assert.That(manual.IsCompiled, Is.False); + Assert.ThrowsAsync(() => + manual.ExecuteAsync(1, 3, KernelArgument.Input(input), KernelArgument.Output(output))); + Assert.That(manual.IsCompiled, Is.False); + Assert.That(output[0], Is.Zero); + + manual.Compile(); + await manual.ExecuteAsync(1, 3, KernelArgument.Input(input), KernelArgument.Output(output)); + Assert.That(output[0], Is.EqualTo(5)); + + gpu.ClearKernelCache(); + Assert.That(manual.IsCompiled, Is.False); + Assert.Throws(() => + manual.Execute(1, 3, KernelArgument.Input(input), KernelArgument.Output(output))); + + var eager = gpu.CreateKernel(Add); + Assert.That(eager.IsCompiled, Is.True); + manual.Execute(1, 4, KernelArgument.Input(input), KernelArgument.Output(output)); + Assert.That(output[0], Is.EqualTo(6)); + } + + [Test] + public static void LazyCompilationCompilesOnFirstLaunch() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(Add, CompilationStrategy.Lazy); + Assert.That(kernel.IsCompiled, Is.False); + int[] result = [0]; + + kernel.Execute(1, 3, ArrayArgument.Input(new[] { 1 }), ArrayArgument.Output(result)); + + Assert.That(kernel.IsCompiled, Is.True); + Assert.That(result[0], Is.EqualTo(4)); + } + + [Test] + public static void NegativeStagingBudgetIsRejected() + { + Assert.Throws(() => new GPU(new() + { + ComputeBackend = ComputeBackend.Cpu, + CudaPinnedStagingCacheBytes = -1 + })); + } + + private static void UnusedReference(string value) { } + + private static void Add(int offset, ArrayView input, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + output[index] = input[index] + offset; + } +} diff --git a/Kernelium/Compilation/KernelCompiler.cs b/Kernelium/Compilation/KernelCompiler.cs index 323b191..7c79a2f 100644 --- a/Kernelium/Compilation/KernelCompiler.cs +++ b/Kernelium/Compilation/KernelCompiler.cs @@ -29,6 +29,16 @@ public ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) return compiled; } } + internal ILGPU.Runtime.Kernel GetCompiled(Delegate kernel) + { + lock (cacheLock) + { + if (kernelCache.TryGetValue(kernel.Method, out var compiled)) + return compiled; + + throw new InvalidOperationException("This kernel uses manual compilation. Call Compile() before launching it."); + } + } public bool IsCompiled(Delegate kernel) { lock (cacheLock) diff --git a/Kernelium/DataTypes/BufferTransferInfo.cs b/Kernelium/DataTypes/BufferTransferInfo.cs new file mode 100644 index 0000000..c8c0d1f --- /dev/null +++ b/Kernelium/DataTypes/BufferTransferInfo.cs @@ -0,0 +1,13 @@ +using Kernelium.Enums; + +namespace Kernelium.DataTypes; + +/// Host-observed information about an explicit buffer transfer. +/// The selected execution backend. +/// The selected device name. +/// Whether the transfer uploads host data. +/// The requested byte count. +/// Host elapsed time, including queueing and cleanup. +/// The transfer exception, if the operation failed. +public sealed record BufferTransferInfo( + ComputeBackend Backend, string DeviceName, bool IsUpload, long Bytes, TimeSpan Elapsed, Exception? Error); diff --git a/Kernelium/DataTypes/GPUConfiguration.cs b/Kernelium/DataTypes/GPUConfiguration.cs index ff5f98f..b8067ca 100644 --- a/Kernelium/DataTypes/GPUConfiguration.cs +++ b/Kernelium/DataTypes/GPUConfiguration.cs @@ -1,13 +1,26 @@ -using Kernelium.Enums; -using System; -using System.Collections.Generic; -using System.Text; +using Kernelium.Enums; -namespace Kernelium.DataTypes +namespace Kernelium.DataTypes; + +public class GPUConfiguration { - public class GPUConfiguration + public ComputeBackend ComputeBackend { get; set; } = ComputeBackend.Auto; + + [Obsolete("Use ComputeBackend instead.")] + public HardwareType HardwareType { - public HardwareType HardwareType { get; set; } = HardwareType.Auto; - public int DeviceIndex { get; set; } = 0; + get => (HardwareType)ComputeBackend; + set => ComputeBackend = (ComputeBackend)value; } + + public int DeviceIndex { get; set; } + + /// Total CUDA pinned staging cache budget in bytes for this GPU. Zero disables caching. + public long CudaPinnedStagingCacheBytes { get; set; } = 384L * 1024 * 1024; + + /// Optional callback invoked after a kernel execution completes or fails. + public Action? ExecutionDiagnostics { get; set; } + + /// Optional callback for explicit buffer uploads and downloads. + public Action? BufferTransferDiagnostics { get; set; } } diff --git a/Kernelium/DataTypes/KernelExecutionInfo.cs b/Kernelium/DataTypes/KernelExecutionInfo.cs new file mode 100644 index 0000000..5fa836d --- /dev/null +++ b/Kernelium/DataTypes/KernelExecutionInfo.cs @@ -0,0 +1,45 @@ +using System.Reflection; +using ILGPU; +using Kernelium.Enums; + +namespace Kernelium.DataTypes; + +/// Host-observed information about one kernel execution. +/// The method supplied to Kernelium. +/// The backend that executed the operation. +/// The selected device name. +/// Whether the operation was submitted asynchronously. +/// The resolved grid and group dimensions, when available. +/// Host elapsed time including queueing, compilation, transfer, and cleanup. +/// Host-array upload bytes requested during marshalling. +/// Host-array download bytes requested during marshalling. +/// The execution exception, when the operation failed. +public sealed record KernelExecutionInfo( + MethodInfo Kernel, + ComputeBackend Backend, + string DeviceName, + bool IsAsync, + KernelConfig? LaunchConfig, + TimeSpan Elapsed, + long UploadBytes, + long DownloadBytes, + Exception? Error) +{ + /// The method name, with compiler-generated local function names simplified. + public string KernelName + { + get + { + string name = Kernel.Name; + int prefix = name.IndexOf(">g__", StringComparison.Ordinal); + if (name.StartsWith('<') && prefix >= 0) + { + int start = prefix + 4; + int end = name.IndexOf('|', start); + if (end > start) + return name[start..end]; + } + return name; + } + } +} diff --git a/Kernelium/Enums/CompilationStrategy.cs b/Kernelium/Enums/CompilationStrategy.cs index 78a02ed..20df377 100644 --- a/Kernelium/Enums/CompilationStrategy.cs +++ b/Kernelium/Enums/CompilationStrategy.cs @@ -1,13 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Kernelium.Enums; -namespace Kernelium.Enums +/// Controls when a kernel is compiled on its accelerator. +public enum CompilationStrategy { - public enum CompilationStrategy - { - Eager, - Lazy, - Manual - } + /// Compile during kernel creation. + Eager, + + /// Compile on the first launch or an explicit call to Compile. + Lazy, + + /// Launch only when a compiled kernel is already in the GPU cache. + Manual } diff --git a/Kernelium/Enums/ComputeBackend.cs b/Kernelium/Enums/ComputeBackend.cs new file mode 100644 index 0000000..c4860f5 --- /dev/null +++ b/Kernelium/Enums/ComputeBackend.cs @@ -0,0 +1,10 @@ +namespace Kernelium.Enums; + +/// Selects the execution backend used by a GPU instance. +public enum ComputeBackend +{ + OpenCL, + Cuda, + Cpu, + Auto +} diff --git a/Kernelium/Enums/HardwareType.cs b/Kernelium/Enums/HardwareType.cs index 3c254c5..5f772f5 100644 --- a/Kernelium/Enums/HardwareType.cs +++ b/Kernelium/Enums/HardwareType.cs @@ -4,6 +4,7 @@ namespace Kernelium.Enums { + [Obsolete("Use ComputeBackend instead.")] public enum HardwareType { OpenCL, diff --git a/Kernelium/Execution/CudaStaging.cs b/Kernelium/Execution/CudaStaging.cs index dc43510..862b803 100644 --- a/Kernelium/Execution/CudaStaging.cs +++ b/Kernelium/Execution/CudaStaging.cs @@ -44,7 +44,7 @@ protected override void DisposeAcceleratorObject(bool disposing) // A stream owns this pool until it drains. Each operation starts at index zero // and rents a distinct region for each argument before enqueueing its transfers. -internal sealed class CudaStagingPool(Accelerator accelerator, long byteBudget = 128L * 1024 * 1024) +internal sealed class CudaStagingPool(Accelerator accelerator, long byteBudget) { private readonly List regions = new(); private long cachedBytes; diff --git a/Kernelium/Execution/DeviceOperations.cs b/Kernelium/Execution/DeviceOperations.cs index 1aa9aa0..1a85279 100644 --- a/Kernelium/Execution/DeviceOperations.cs +++ b/Kernelium/Execution/DeviceOperations.cs @@ -1,4 +1,8 @@ using System.Collections.Concurrent; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Kernelium.DataTypes; +using Kernelium.Enums; using ILGPU.Runtime; namespace Kernelium.Execution; @@ -9,30 +13,45 @@ internal sealed class DeviceOperations // accelerator and its retained resources rooted until process exit. private static readonly ConcurrentBag undrainedDevices = new(); - private sealed class Slot + private sealed class Slot(long stagingBudget) { internal AcceleratorStream? Stream; internal CudaStagingPool? Staging; + internal long StagingBudget = stagingBudget; } private readonly Accelerator accelerator; private readonly bool isCpu; + private readonly Action? transferDiagnostics; + internal ComputeBackend Backend { get; } + internal string DeviceName { get; } private readonly OperationScheduler.Resource defaultStream = new(); private readonly ConcurrentQueue slots = new(); private readonly SemaphoreSlim available; private readonly ConcurrentBag retained = new(); - private readonly Slot defaultSlot = new(); + private readonly Slot defaultSlot; internal OperationScheduler.Resource Lifetime { get; } = new(); - internal DeviceOperations(Accelerator accelerator) + internal DeviceOperations(Accelerator accelerator, long cudaStagingBudget = 0, + Action? transferDiagnostics = null) { this.accelerator = accelerator; + this.transferDiagnostics = transferDiagnostics; + Backend = accelerator.AcceleratorType switch + { + AcceleratorType.Cuda => ComputeBackend.Cuda, + AcceleratorType.OpenCL => ComputeBackend.OpenCL, + _ => ComputeBackend.Cpu + }; + DeviceName = accelerator.Device.Name; isCpu = accelerator.AcceleratorType == AcceleratorType.CPU; int count = isCpu ? 1 : 2; available = new(count, count); + long perStreamBudget = cudaStagingBudget / (count + 1); + defaultSlot = new Slot(perStreamBudget + cudaStagingBudget % (count + 1)); for (int i = 0; i < count; i++) - slots.Enqueue(new Slot()); + slots.Enqueue(new Slot(perStreamBudget)); } internal OperationScheduler.Claims GetClaims(bool useDefaultStream) @@ -107,8 +126,8 @@ await Task.Run(() => private T RunOnStream(Slot slot, AcceleratorStream stream, MemoryBuffer[] allocations, Func action, Action retire) { - if (accelerator.AcceleratorType == AcceleratorType.Cuda) - slot.Staging ??= new CudaStagingPool(accelerator); + if (slot.StagingBudget > 0 && accelerator.AcceleratorType == AcceleratorType.Cuda) + slot.Staging ??= new CudaStagingPool(accelerator, slot.StagingBudget); var work = new StreamWork(stream, retained, allocations, slot.Staging); try { @@ -125,12 +144,45 @@ private T RunOnStream(Slot slot, AcceleratorStream stream, MemoryBuffer[] all { retained.Add(staging); slot.Staging = null; + // The retained pool still counts toward the device budget. + slot.StagingBudget = 0; } retire(); } } } + internal TResult ObserveTransfer(int length, bool upload, Func transfer) + where T : unmanaged + { + if (transferDiagnostics is null) + return transfer(); + + long started = Stopwatch.GetTimestamp(); + Exception? error = null; + try + { + return transfer(); + } + catch (Exception failure) + { + error = failure; + throw; + } + finally + { + try + { + transferDiagnostics(new BufferTransferInfo(Backend, DeviceName, upload, + (long)length * Unsafe.SizeOf(), Stopwatch.GetElapsedTime(started), error)); + } + catch (Exception) + { + // Diagnostic observers cannot change the result of a transfer. + } + } + } + internal T UseAccelerator(Func action) { using var reservation = OperationScheduler.Reserve(GetClaims(useDefaultStream: false)); diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index ef5a741..7fbb418 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -1,6 +1,9 @@ -using ILGPU; +using System.Diagnostics; +using ILGPU; using ILGPU.Runtime; using Kernelium.Compilation; +using Kernelium.DataTypes; +using Kernelium.Enums; using Kernelium.Memory; namespace Kernelium.Execution @@ -11,6 +14,14 @@ internal sealed class KernelExecutor private readonly KernelCompiler compiler; private readonly ParameterMarshaller marshaller; private readonly DeviceOperations operations; + private readonly Action? diagnostics; + + private sealed class ExecutionMeasurement + { + internal long StartedAt { get; } = Stopwatch.GetTimestamp(); + internal KernelConfig? Config; + internal StreamWork? Work; + } internal LaunchSizing Sizing { get; } @@ -18,29 +29,80 @@ public KernelExecutor( Accelerator accelerator, KernelCompiler compiler, ParameterMarshaller marshaller, - DeviceOperations operations) + DeviceOperations operations, + Action? diagnostics) { this.accelerator = accelerator; this.compiler = compiler; this.marshaller = marshaller; this.operations = operations; + this.diagnostics = diagnostics; Sizing = new LaunchSizing(accelerator); } - internal void Execute(Delegate kernel, Func getConfig, object[] parameters) + internal void Execute(Kernel kernel, Func getConfig, + object[] parameters, Action? validateExtent = null) + { + var measurement = diagnostics is null ? null : new ExecutionMeasurement(); + Exception? error = null; + try + { + validateExtent?.Invoke(); + var (captured, claims, allocations) = Capture(kernel.Method, parameters, useDefaultStream: true); + operations.Run(claims, allocations, work => + { + Launch(kernel, getConfig, captured, work, measurement); + return true; + }); + } + catch (Exception failure) + { + error = failure; + throw; + } + finally + { + Report(kernel.Method, isAsync: false, measurement, error); + } + } + + internal async Task ExecuteAsync(Kernel kernel, Func getConfig, + object[] parameters, Action? validateExtent = null) { - var (captured, claims, allocations) = Capture(kernel, parameters, useDefaultStream: true); - operations.Run(claims, allocations, work => + var measurement = diagnostics is null ? null : new ExecutionMeasurement(); + Exception? error = null; + try { - Launch(kernel, getConfig, captured, work); - return true; - }); + validateExtent?.Invoke(); + var (captured, claims, allocations) = Capture(kernel.Method, parameters, useDefaultStream: false); + await operations.RunAsync(claims, allocations, work => Launch(kernel, getConfig, captured, work, measurement)) + .ConfigureAwait(false); + } + catch (Exception failure) + { + error = failure; + throw; + } + finally + { + Report(kernel.Method, isAsync: true, measurement, error); + } } - internal async Task ExecuteAsync(Delegate kernel, Func getConfig, object[] parameters) + private void Report(Delegate kernel, bool isAsync, ExecutionMeasurement? measurement, Exception? error) { - var (captured, claims, allocations) = Capture(kernel, parameters, useDefaultStream: false); - await operations.RunAsync(claims, allocations, work => Launch(kernel, getConfig, captured, work)) - .ConfigureAwait(false); + if (measurement is null) + return; + + try + { + diagnostics!(new KernelExecutionInfo(kernel.Method, operations.Backend, operations.DeviceName, isAsync, + measurement.Config, Stopwatch.GetElapsedTime(measurement.StartedAt), + measurement.Work?.UploadBytes ?? 0, measurement.Work?.DownloadBytes ?? 0, error)); + } + catch (Exception) + { + // Diagnostic observers cannot change the result of a launch. + } } private (object[] Parameters, OperationScheduler.Claims Claims, MemoryBuffer[] Allocations) Capture( @@ -55,11 +117,19 @@ await operations.RunAsync(claims, allocations, work => Launch(kernel, getConfig, return (captured, claims, marshaller.Capture(captured, claims)); } - private void Launch(Delegate kernel, Func getConfig, - object[] parameters, StreamWork work) + private void Launch(Kernel kernel, Func getConfig, + object[] parameters, StreamWork work, ExecutionMeasurement? measurement) { - var compiled = compiler.GetOrCompile(kernel); + var compiled = kernel.Strategy == CompilationStrategy.Manual + ? compiler.GetCompiled(kernel.Method) + : compiler.GetOrCompile(kernel.Method); var config = getConfig(compiled); + if (measurement is not null) + { + measurement.Config = config; + measurement.Work = work; + work.MeasureTransfers = true; + } Sizing.ValidateCpuLaunchSize(config); marshaller.MarshalForLaunch(work, parameters); // CUDA's parameterless wrapper has one unused argument. diff --git a/Kernelium/Execution/StreamWork.cs b/Kernelium/Execution/StreamWork.cs index 617070d..6df3652 100644 --- a/Kernelium/Execution/StreamWork.cs +++ b/Kernelium/Execution/StreamWork.cs @@ -21,6 +21,9 @@ internal sealed class StreamWork( internal AcceleratorStream Stream => stream; internal bool Retired { get; private set; } + internal bool MeasureTransfers { get; set; } + internal long UploadBytes { get; private set; } + internal long DownloadBytes { get; private set; } internal void Own(IDisposable resource) => temporary.Add(resource); internal void KeepAlive(object resource) => held.Add(resource); @@ -54,6 +57,14 @@ void IArrayTransfers.TransferArray(MemoryBuffer1D buffer, { Own(buffer); ArrayView view = buffer.View; + if (MeasureTransfers) + { + long bytes = CudaStaging.ByteCount(data.Length); + if (copyIn) + UploadBytes += bytes; + if (copyOut) + DownloadBytes += bytes; + } if (data.Length == 0) return; diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index 2592d1a..dfffd63 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -29,26 +29,30 @@ public class GPU : IDisposable public GPU(GPUConfiguration? config = null) { + config ??= new GPUConfiguration(); + long stagingBudget = config.CudaPinnedStagingCacheBytes; + ArgumentOutOfRangeException.ThrowIfNegative(stagingBudget, nameof(config.CudaPinnedStagingCacheBytes)); + context = Context.CreateDefault(); try { - config ??= new GPUConfiguration(); - accelerator = config.HardwareType switch + accelerator = config.ComputeBackend 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), + ComputeBackend.Cuda => context.CreateCudaAccelerator(config.DeviceIndex), + ComputeBackend.OpenCL => context.CreateCLAccelerator(config.DeviceIndex), + ComputeBackend.Cpu => context.CreateCPUAccelerator(config.DeviceIndex), + ComputeBackend.Auto => context.GetPreferredDevice(false).CreateAccelerator(context), _ => throw new NotSupportedException() }; - operations = new DeviceOperations(accelerator); + operations = new DeviceOperations(accelerator, stagingBudget, config.BufferTransferDiagnostics); compiler = new KernelCompiler(accelerator); marshaller = new ParameterMarshaller(accelerator); executor = new KernelExecutor( accelerator, compiler, marshaller, - operations + operations, + config.ExecutionDiagnostics ); } catch @@ -57,13 +61,63 @@ public GPU(GPUConfiguration? config = null) throw; } } - public Kernel GenerateKernel(Delegate kernel, bool precompile = true) + [Obsolete("Use CreateKernel instead.")] + public Kernel GenerateKernel(Delegate kernel, bool precompile = true) => + CreateKernel(kernel, precompile); + + public Kernel CreateKernel(Delegate kernel, CompilationStrategy strategy = CompilationStrategy.Eager) { - var instance = new Kernel(this, kernel); - if (precompile) + var instance = new Kernel(this, kernel, strategy); + if (strategy == CompilationStrategy.Eager) instance.Compile(); return instance; } + + public Kernel CreateKernel(Delegate kernel, bool precompile) => + CreateKernel(kernel, precompile ? CompilationStrategy.Eager : CompilationStrategy.Lazy); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + + public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => + new(CreateKernel(kernel, strategy)); + + public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => + new(CreateKernel(kernel, precompile)); + internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) { return operations.UseAccelerator(() => compiler.GetOrCompile(kernel)); @@ -76,38 +130,32 @@ public void ClearKernelCache() { compiler.Clear(); } - internal void Execute(Delegate kernel, KernelConfig config, object[] parameters) => + internal void Execute(Kernel kernel, KernelConfig config, object[] parameters) => executor.Execute(kernel, _ => config, parameters); - internal void Execute(Delegate kernel, int workItems, object[] parameters) - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems); - executor.Execute(kernel, compiled => executor.Sizing.For1D(compiled, workItems), parameters); - } + internal void Execute(Kernel kernel, int workItems, object[] parameters) => + executor.Execute(kernel, compiled => executor.Sizing.For1D(compiled, workItems), parameters, + () => ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems)); - internal void Execute2D(Delegate kernel, int width, int height, object[] parameters) - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - executor.Execute(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters); - } + internal void Execute2D(Kernel kernel, int width, int height, object[] parameters) => + executor.Execute(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters, + () => Validate2DExtent(width, height)); - internal Task ExecuteAsync(Delegate kernel, KernelConfig config, object[] parameters) => + internal Task ExecuteAsync(Kernel kernel, KernelConfig config, object[] parameters) => executor.ExecuteAsync(kernel, _ => config, parameters); - internal async Task ExecuteAsync(Delegate kernel, int workItems, object[] parameters) - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems); - await executor.ExecuteAsync(kernel, compiled => executor.Sizing.For1D(compiled, workItems), parameters) - .ConfigureAwait(false); - } + internal Task ExecuteAsync(Kernel kernel, int workItems, object[] parameters) => + executor.ExecuteAsync(kernel, compiled => executor.Sizing.For1D(compiled, workItems), parameters, + () => ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems)); + + internal Task Execute2DAsync(Kernel kernel, int width, int height, object[] parameters) => + executor.ExecuteAsync(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters, + () => Validate2DExtent(width, height)); - internal async Task Execute2DAsync(Delegate kernel, int width, int height, object[] parameters) + private static void Validate2DExtent(int width, int height) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - await executor.ExecuteAsync(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters) - .ConfigureAwait(false); } public object[] ConvertParameters( @@ -128,7 +176,8 @@ public GPUBuffer Allocate(int length) where T : unmanaged => public GPUBuffer Upload(T[] data) where T : unmanaged { ArgumentNullException.ThrowIfNull(data); - return CreateBuffer(data.Length, data); + return operations.ObserveTransfer>(data.Length, upload: true, + () => CreateBuffer(data.Length, data)); } private GPUBuffer CreateBuffer(int length, T[]? data) where T : unmanaged diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index e06019b..fe75a46 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -1,5 +1,6 @@ using ILGPU; using Kernelium.Compilation; +using Kernelium.Enums; namespace Kernelium { @@ -8,32 +9,41 @@ public class Kernel public Delegate Method { get; } public GPU GPU { get; } public bool IsCompiled => GPU.IsCompiled(Method); - public Kernel(GPU gpu, Delegate method) + internal CompilationStrategy Strategy { get; } + + public Kernel(GPU gpu, Delegate method) : this(gpu, method, CompilationStrategy.Lazy) + { + } + + internal Kernel(GPU gpu, Delegate method, CompilationStrategy strategy) { ArgumentNullException.ThrowIfNull(gpu); + if (!Enum.IsDefined(strategy)) + throw new ArgumentOutOfRangeException(nameof(strategy)); KernelCompiler.ValidateKernel(method); + Strategy = strategy; GPU = gpu; Method = 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); + public void Execute(KernelConfig config, params object[] parameters) => GPU.Execute(this, config, parameters); + public void Execute(int workItems, params object[] parameters) => GPU.Execute(this, 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); + GPU.Execute2D(this, width, height, parameters); /// Submits a one-dimensional workload and completes after host copy-back. public Task ExecuteAsync(int workItems, params object[] parameters) => - GPU.ExecuteAsync(Method, workItems, parameters); + GPU.ExecuteAsync(this, workItems, parameters); /// Submits a workload with explicit grid and group dimensions. public Task ExecuteAsync(KernelConfig config, params object[] parameters) => - GPU.ExecuteAsync(Method, config, parameters); + GPU.ExecuteAsync(this, config, parameters); /// Submits a two-dimensional workload with an automatically sized group. /// Guard both global indices against the logical width and height. public Task Execute2DAsync(int width, int height, params object[] parameters) => - GPU.Execute2DAsync(Method, width, height, parameters); + GPU.Execute2DAsync(this, width, height, parameters); } } \ No newline at end of file diff --git a/Kernelium/KernelArgument.cs b/Kernelium/KernelArgument.cs new file mode 100644 index 0000000..4384aa6 --- /dev/null +++ b/Kernelium/KernelArgument.cs @@ -0,0 +1,44 @@ +using ILGPU; +using Kernelium.Memory; + +namespace Kernelium; + +/// An argument for a kernel parameter of type . +public readonly struct KernelArgument +{ + private readonly object? value; + + internal KernelArgument(object? value) => this.value = value; + + // The default wrapper represents default(T). A null reference is + // validated by the same launch pipeline as an untyped null argument. + internal object Value => value ?? (object)default(T)!; + + public static implicit operator KernelArgument(T value) => new(value); +} + +/// Adapts host arrays and device buffers to typed array-view parameters. +public static class KernelArgument +{ + /// Uploads the array and copies it back after a successful launch. + public static KernelArgument> ReadWrite(T[] array) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(array); + return new(array); + } + + /// Uploads the array before launch. + public static KernelArgument> Input(T[] array) where T : unmanaged => + new(ArrayArgument.Input(array)); + + /// Copies the array back after a successful launch. + public static KernelArgument> Output(T[] array) where T : unmanaged => + new(ArrayArgument.Output(array)); + + /// Passes an existing device allocation to the kernel. + public static KernelArgument> Buffer(GPUBuffer buffer) where T : unmanaged + { + ArgumentNullException.ThrowIfNull(buffer); + return new(buffer); + } +} diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index 62105ba..d913d03 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -7,7 +7,7 @@ true true Kernelium - 0.3.1 + 1.0.0 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 @@ -15,6 +15,7 @@ https://github.com/Hinterdorfer-Raphael/Kernelium git README.md + First stable release of Kernelium. Run synchronous and asynchronous C# compute kernels on CUDA, OpenCL, and CPU with typed launch arguments, configurable CUDA pinned staging, and opt-in execution diagnostics. Use CreateKernel and ComputeBackend in new code. MIT true snupkg diff --git a/Kernelium/Memory/GPUBuffer.cs b/Kernelium/Memory/GPUBuffer.cs index 7bdf707..91923b9 100644 --- a/Kernelium/Memory/GPUBuffer.cs +++ b/Kernelium/Memory/GPUBuffer.cs @@ -43,24 +43,28 @@ internal GPUBuffer(Accelerator accelerator, DeviceOperations operations, int len public void Upload(T[] data) { ArgumentNullException.ThrowIfNull(data); - Transfer(data, upload: true); + operations.ObserveTransfer(data.Length, upload: true, () => Transfer(data, upload: true)); } public T[] Download() { - ThrowIfDisposed(); - var result = new T[Length]; - Download(result); - return result; + return operations.ObserveTransfer(checked((int)Length), upload: false, () => + { + ThrowIfDisposed(); + var result = new T[Length]; + Transfer(result, upload: false); + return result; + }); } public void Download(T[] destination) { ArgumentNullException.ThrowIfNull(destination); - Transfer(destination, upload: false); + operations.ObserveTransfer(destination.Length, upload: false, + () => Transfer(destination, upload: false)); } - private void Transfer(T[] data, bool upload) + private bool Transfer(T[] data, bool upload) { var view = View; if (data.LongLength != Length) @@ -69,7 +73,7 @@ private void Transfer(T[] data, bool upload) var claims = operations.GetClaims(useDefaultStream: true); claims.Add(lifetime, write: upload); claims.Add(OperationScheduler.For(data), write: !upload); - operations.Run(claims, [Allocation], work => + return operations.Run(claims, [Allocation], work => { if (upload) work.Upload(view, data); diff --git a/Kernelium/TypedKernel.cs b/Kernelium/TypedKernel.cs new file mode 100644 index 0000000..0330525 --- /dev/null +++ b/Kernelium/TypedKernel.cs @@ -0,0 +1,213 @@ +using ILGPU; + +namespace Kernelium; + +/// A kernel with no launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems) => + kernel.Execute(workItems); + + public void Execute(KernelConfig config) => + kernel.Execute(config); + + public void Execute2D(int width, int height) => + kernel.Execute2D(width, height); + + public Task ExecuteAsync(int workItems) => + kernel.ExecuteAsync(workItems); + + public Task ExecuteAsync(KernelConfig config) => + kernel.ExecuteAsync(config); + + public Task Execute2DAsync(int width, int height) => + kernel.Execute2DAsync(width, height); +} + +/// A kernel with 1 statically typed launch argument. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1) => + kernel.Execute(workItems, argument1.Value); + + public void Execute(KernelConfig config, KernelArgument argument1) => + kernel.Execute(config, argument1.Value); + + public void Execute2D(int width, int height, KernelArgument argument1) => + kernel.Execute2D(width, height, argument1.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1) => + kernel.ExecuteAsync(workItems, argument1.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1) => + kernel.ExecuteAsync(config, argument1.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1) => + kernel.Execute2DAsync(width, height, argument1.Value); +} + +/// A kernel with 2 statically typed launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute(workItems, argument1.Value, argument2.Value); + + public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute(config, argument1.Value, argument2.Value); + + public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute2D(width, height, argument1.Value, argument2.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2) => + kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2) => + kernel.ExecuteAsync(config, argument1.Value, argument2.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value); +} + +/// A kernel with 3 statically typed launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value); + + public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value); + + public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value); +} + +/// A kernel with 4 statically typed launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + + public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + + public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value); +} + +/// A kernel with 5 statically typed launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + + public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + + public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); +} + +/// A kernel with 6 statically typed launch arguments. +public sealed class TypedKernel +{ + private readonly Kernel kernel; + + internal TypedKernel(Kernel kernel) => this.kernel = kernel; + + public bool IsCompiled => kernel.IsCompiled; + + public void Compile() => kernel.Compile(); + + public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + + public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + + public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + + public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + + public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + + public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => + kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); +} diff --git a/Kernelium/TypedKernelExtensions.cs b/Kernelium/TypedKernelExtensions.cs new file mode 100644 index 0000000..d2e5eee --- /dev/null +++ b/Kernelium/TypedKernelExtensions.cs @@ -0,0 +1,55 @@ +using ILGPU; + +namespace Kernelium; + +/// Launches typed 2D kernels that receive their logical extent as a first parameter. +public static class TypedKernelExtensions +{ + public static void Execute2D(this TypedKernel kernel, + Index2D extent) => + kernel.Execute2D(extent.X, extent.Y, extent); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent) => + kernel.Execute2DAsync(extent.X, extent.Y, extent); + + public static void Execute2D(this TypedKernel kernel, + Index2D extent, KernelArgument argument1) => + kernel.Execute2D(extent.X, extent.Y, extent, argument1); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent, KernelArgument argument1) => + kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1); + + public static void Execute2D(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2) => + kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2); + + public static void Execute2D(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3); + + public static void Execute2D(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + + public static void Execute2D(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); + + public static Task Execute2DAsync(this TypedKernel kernel, + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); +} diff --git a/README.md b/README.md index d09872c..2a9dffd 100644 --- a/README.md +++ b/README.md @@ -10,25 +10,47 @@ Kernelium is MIT licensed and targets .NET 10. ## Install -This README documents Kernelium 0.3.1. Install the package from NuGet: +Install Kernelium 1.0.0 in a .NET 10 project. ```sh -dotnet add package Kernelium --version 0.3.1 +dotnet add package Kernelium --version 1.0.0 ``` To build against the checkout, add a project reference to `Kernelium/Kernelium.csproj`. +## What's in 1.0.0 + +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. For 1.0.0, use +`gpu.CreateKernel(...)` and `ComputeBackend = ComputeBackend.Cpu` in place of +the preview names `GenerateKernel` and `HardwareType`. The preview names +remain available as obsolete aliases. + +Use `CreateTypedKernel` for compile-time argument checks, +`GPUConfiguration.CudaPinnedStagingCacheBytes` to tune CUDA staging, and +`GPUConfiguration.ExecutionDiagnostics` to observe launches. + ## Quickstart -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. +For a fresh project, run the following commands. + +```sh +dotnet new console -n KerneliumQuickstart -f net10.0 +cd KerneliumQuickstart +dotnet add package Kernelium --version 1.0.0 +``` + +Replace `Program.cs` with the code below and run `dotnet run`. The CPU backend +makes the example runnable without a GPU. ```csharp using ILGPU; using Kernelium; using Kernelium.Enums; -using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); -var add = gpu.GenerateKernel(VectorAdd); +using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); +var add = gpu.CreateKernel(VectorAdd); float[] left = [1f, 2f, 3f]; float[] right = [10f, 20f, 30f]; @@ -49,21 +71,24 @@ The example uses equal-length arrays. Kernelium can round the launch up to a ful | Backend | When to use it | |---|---| -| `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 | +| `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. ## API at a glance | Task | API | |---|---| -| Select an accelerator | `new GPU(new() { HardwareType = HardwareType.Cuda })` | +| 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.GenerateKernel(VectorAdd)` | +| Compile a static C# kernel | `gpu.CreateKernel(VectorAdd)` | +| Check launch arguments at compile time | `gpu.CreateTypedKernel(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(length)` | @@ -75,7 +100,7 @@ The package ships `llms.txt`, a compact reference to the same APIs and resource ## Benchmarks -The November 28 release run measured 72 cases on a Ryzen 7 5700G and RTX 4060 Ti. +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. @@ -92,7 +117,7 @@ The `GPU` class represents an accelerator instance and manages kernel compilatio #### Inspect the selected device `gpu.Device` describes the accelerator that was actually selected, including -when the configuration uses `HardwareType.Auto`. +when the configuration uses `ComputeBackend.Auto`. ```csharp var device = gpu.Device; @@ -123,20 +148,32 @@ Async launches use Kernelium-owned streams on CUDA and OpenCL. Coordinate depend across streams and keep resources alive when using direct ILGPU calls or `gpu.ConvertParameters`, which are outside Kernelium's operation tracking. -#### GenerateKernel +#### CreateKernel Creates a reusable kernel associated with the GPU instance. ```csharp -var kernel = gpu.GenerateKernel(VectorAdd); +var kernel = gpu.CreateKernel(VectorAdd); ``` -Kernels compile immediately by default. Pass `precompile: false` to defer compilation until the first launch: +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 | ```csharp -var kernel = gpu.GenerateKernel(VectorAdd, precompile: false); +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. Existing +`precompile: false` calls are equivalent to `CompilationStrategy.Lazy`. + 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. @@ -203,7 +240,9 @@ add.Execute(result.Length, left, right, result); // result contains [11f, 22f, 33f]. ``` -Each array argument gets its own temporary device allocation. Kernelium uploads every +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 @@ -257,10 +296,24 @@ CUDA and OpenCL have two async streams per GPU and can overlap independent workl 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. -On CUDA, each active stream can cache up to 128 MiB of pinned host staging -memory on demand. The default stream and two async streams can cache up to -384 MiB per GPU instance in total, with additional temporary staging possible -when a transfer exceeds the available cache budget. +### Configure CUDA pinned staging + +CUDA caches up to 384 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. + +```csharp +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. ### Launch a 2D workload @@ -280,12 +333,16 @@ static void DoublePixel(int width, int height, ArrayView input, ArrayView` uses its exi 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. Each stream caches up to 128 MiB of pinned staging. Transfers that do -not fit the cache use temporary staging that is released after the stream drains. On Windows and Linux, an explicit `GPUBuffer.Download` uses a +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. Repeated disposal is safe. +### Check kernel arguments at compile time + +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. + +```csharp +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`. `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. + +### Observe kernel executions + +Set `ExecutionDiagnostics` when constructing a GPU to receive a report after +each launch attempt, including invalid extents and arguments. + +```csharp +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. + ## Architecture ```text diff --git a/llms.txt b/llms.txt index d3acc9b..a9c88bd 100644 --- a/llms.txt +++ b/llms.txt @@ -4,7 +4,7 @@ ## Install and check the version -- This file documents Kernelium 0.3.1. Install it with `dotnet add package Kernelium --version 0.3.1`. To build against the checkout, add a project reference to `Kernelium/Kernelium.csproj`. +- This file documents Kernelium 1.0.0. Install it with `dotnet add package Kernelium --version 1.0.0`. To build against the checkout, add a project reference to `Kernelium/Kernelium.csproj`. ## Quickstart @@ -15,8 +15,8 @@ using ILGPU; using Kernelium; using Kernelium.Enums; -using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); -var kernel = gpu.GenerateKernel(DoubleValues); +using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); +var kernel = gpu.CreateKernel(DoubleValues); int[] input = [1, 2, 3]; var output = new int[input.Length]; @@ -34,9 +34,10 @@ static void DoubleValues(ArrayView input, ArrayView output) ## 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)`. +- Set `ComputeBackend.Cuda` for a CUDA-capable NVIDIA device, `ComputeBackend.OpenCL` for a compatible OpenCL runtime, or `ComputeBackend.Auto` for ILGPU's preferred available device. `DeviceIndex` selects a device for an explicit backend. +- An explicit backend requires the corresponding runtime and device. GPU construction throws if the backend or device is unavailable. +- `CreateKernel` compiles eagerly by default. Both kernel factories accept `CompilationStrategy`. `Eager` compiles at creation, `Lazy` compiles on the first launch, and `Manual` requires a compiled cache entry before launch. Use `Compile()` to populate that entry. `precompile: false` still selects lazy 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. The work-item count, width, and height must be positive. 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. Kernels must be static methods or non-capturing lambdas that return `void`. Use ILGPU's supported subset of C# and write results through `ArrayView`. - For a parameterless CUDA kernel, use a named static method with the ILGPU 1.5.3 compatibility wrapper. @@ -60,11 +61,20 @@ await Task.WhenAll( ## 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. +- Host-array arguments must be one-dimensional `T[]` arrays with unmanaged elements. Flatten 2D data before passing it. 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` or `ExecuteAsync` and call `destination.Download(output)` when the host needs the result. -- On CUDA, each stream reuses pinned host staging for array arguments and buffer uploads. A read/write argument uses the same region for both directions. Each stream caches up to 128 MiB of pinned staging. Transfers that exceed the available cache use temporary staging. On Windows and Linux, explicit buffer downloads copy directly into the destination array. +- On CUDA, `GPUConfiguration.CudaPinnedStagingCacheBytes` defaults to 384 MiB total, shared among the default stream and two async streams. Set it to `0` to disable caching. Transfers that exceed the available cache use temporary pinned staging. On Windows and Linux, explicit buffer downloads copy directly into the destination array. - Use buffers with the GPU that created them. Keep intermediate results on the device across launches and download explicitly. Buffer and GPU disposal reject new operations, drain accepted operations including queued uses, and release resources. Repeated disposal is safe. If a driver failure leaves retained work with unknown completion at teardown, disposal throws and preserves the affected resources until process exit. +## Typed launches and diagnostics + +- For a typed kernel whose first parameter is `Index2D`, use `Execute2D(extent, ...)` or `Execute2DAsync(extent, ...)` to size the launch and pass the same extent into the kernel. + +- Use `gpu.CreateTypedKernel(Method)` for zero to six kernel parameters. To infer the types, first assign the method group to a local variable. The typed launch checks count and types at compile time. Pass scalars and views directly. Use `KernelArgument.Input`, `Output`, or `ReadWrite` for host arrays and `KernelArgument.Buffer` for a device buffer. +- Set `GPUConfiguration.ExecutionDiagnostics` to receive a `KernelExecutionInfo` report after each launch attempt, including invalid extents and arguments. Reports include the selected backend and device, resolved launch dimensions when available, requested host-array transfer bytes, host elapsed time, and any exception. Use `KernelName` for readable local function names. Callbacks may run concurrently. +- Set `GPUConfiguration.BufferTransferDiagnostics` to observe explicit buffer uploads and downloads. Reports include direction, requested bytes, device, host elapsed time, and any exception. +- `CreateKernel` and `ComputeBackend` replace the obsolete preview names `GenerateKernel` and `HardwareType`. + ## ILGPU interop - `gpu.Device` reports the actual selected backend and device name, along with memory size, grid and group limits, and backend capabilities. @@ -73,7 +83,7 @@ await Task.WhenAll( ## Benchmarks -- The November 28 report covers 72 cases, including serial and async CPU and CUDA batch submission with output readback and synchronous comparisons against native C# and raw ILGPU. The benchmark harness was run from a separate local workspace. OpenCL was outside the scope of this run. [Benchmark results](https://github.com/Hinterdorfer-Raphael/Kernelium/blob/main/benchmarks/results/2026-11-28.md) +- The November 28, 2026 Kernelium 0.3.0 report covers 72 cases, including serial and async CPU and CUDA batch submission with output readback and synchronous comparisons against native C# and raw ILGPU. The benchmark harness was run from a separate local workspace. OpenCL was outside the scope of this run. [Benchmark results](https://github.com/Hinterdorfer-Raphael/Kernelium/blob/main/benchmarks/results/2026-11-28.md) ## Documentation From bd66eda9bfa64172b1cb3ec3110385151a9b4dcd Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 18:53:54 +0100 Subject: [PATCH 02/11] Restrict NuGet releases to main --- .github/workflows/nuget.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index ad37c1a..b6e0685 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -4,7 +4,7 @@ on: pull_request: push: branches: - - '**' + - main tags: - 'v*' @@ -16,6 +16,15 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Require release commit on main + if: github.ref_type == 'tag' + run: | + if ! git merge-base --is-ancestor HEAD refs/remotes/origin/main; then + echo "::error::Release tags must point to a commit on main." + exit 1 + fi - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0.x' From 3ad697714e6027644ffe02e0c0576b6f1c2bc386 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:00:11 +0100 Subject: [PATCH 03/11] Add reproducible benchmark harness --- README.md | 2 +- .../Kernelium.Benchmarks/BenchmarkProgress.cs | 44 ++++ .../ComputeBenchmarks.Batches.cs | 170 ++++++++++++++++ .../ComputeBenchmarks.Device.cs | 158 +++++++++++++++ .../Kernelium.Benchmarks/ComputeBenchmarks.cs | 189 ++++++++++++++++++ .../Kernelium.Benchmarks.csproj | 14 ++ .../Kernelium.Benchmarks.slnx | 4 + .../Kernelium.Benchmarks/NativeThreads.cs | 72 +++++++ benchmarks/Kernelium.Benchmarks/Program.cs | 129 ++++++++++++ benchmarks/Kernelium.Benchmarks/README.md | 148 ++++++++++++++ 10 files changed, 929 insertions(+), 1 deletion(-) create mode 100644 benchmarks/Kernelium.Benchmarks/BenchmarkProgress.cs create mode 100644 benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Batches.cs create mode 100644 benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Device.cs create mode 100644 benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.cs create mode 100644 benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.csproj create mode 100644 benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.slnx create mode 100644 benchmarks/Kernelium.Benchmarks/NativeThreads.cs create mode 100644 benchmarks/Kernelium.Benchmarks/Program.cs create mode 100644 benchmarks/Kernelium.Benchmarks/README.md diff --git a/README.md b/README.md index 2a9dffd..64ffa5a 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ 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. -The benchmark harness was run from a separate local workspace. +Run the [benchmark harness](https://github.com/Hinterdorfer-Raphael/Kernelium/tree/main/benchmarks/Kernelium.Benchmarks) from a source checkout. [Full benchmark results](https://github.com/Hinterdorfer-Raphael/Kernelium/blob/main/benchmarks/results/2026-11-28.md) ## API Documentation diff --git a/benchmarks/Kernelium.Benchmarks/BenchmarkProgress.cs b/benchmarks/Kernelium.Benchmarks/BenchmarkProgress.cs new file mode 100644 index 0000000..74723d4 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/BenchmarkProgress.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using BenchmarkDotNet.EventProcessors; +using BenchmarkDotNet.Reports; +using BenchmarkDotNet.Running; + +internal sealed class BenchmarkProgress : EventProcessor +{ + private const int BarWidth = 24; + private long started; + private int completed; + private int total; + + public override void OnStartRunBenchmarksInType(Type type, IReadOnlyList benchmarks) + { + started = Stopwatch.GetTimestamp(); + completed = 0; + total = benchmarks.Count; + if (total > 0) + WriteProgress(); + } + + public override void OnEndRunBenchmark(BenchmarkCase benchmarkCase, BenchmarkReport report) + { + completed++; + WriteProgress(); + } + + private void WriteProgress() + { + int filled = completed * BarWidth / total; + string bar = new string('#', filled) + new string('-', BarWidth - filled); + double percent = 100.0 * completed / total; + string eta = "calculating"; + + if (completed > 0) + { + double secondsPerCase = Stopwatch.GetElapsedTime(started).TotalSeconds / completed; + var remaining = TimeSpan.FromSeconds(Math.Ceiling(secondsPerCase * (total - completed))); + eta = $"{(int)remaining.TotalHours:D2}:{remaining.Minutes:D2}:{remaining.Seconds:D2}"; + } + + Console.WriteLine($"Progress [{bar}] {completed}/{total} ({percent:F0}%) | Est. remaining: {eta}"); + } +} diff --git a/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Batches.cs b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Batches.cs new file mode 100644 index 0000000..e05f6a1 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Batches.cs @@ -0,0 +1,170 @@ +using BenchmarkDotNet.Attributes; +using Kernelium; +using Kernelium.Enums; + +public partial class ComputeBenchmarks +{ + private const int BatchCount = 2; + private KerneliumBatch[]? batches; + private NativeThreads? submissionWorkers; + private readonly Exception?[] submissionErrors = new Exception?[BatchCount]; + + private sealed record KerneliumBatch(Action Execute, Func ExecuteAsync, Action Download, int[] Result); + + [GlobalSetup(Target = nameof(KerneliumCpuSerialBatches))] + public void SetupKerneliumCpuSerialBatches() => PrepareBatches(ComputeBackend.Cpu, KerneliumCpuSerialBatches); + + [GlobalSetup(Target = nameof(KerneliumCpuAsyncBatches))] + public void SetupKerneliumCpuAsyncBatches() => PrepareBatches(ComputeBackend.Cpu, () => KerneliumCpuAsyncBatches().GetAwaiter().GetResult()); + + [GlobalSetup(Target = nameof(KerneliumCpuThreadedAsyncBatches))] + public void SetupKerneliumCpuThreadedAsyncBatches() => PrepareBatches(ComputeBackend.Cpu, KerneliumCpuThreadedAsyncBatches, threaded: true); + + [GlobalSetup(Target = nameof(KerneliumOpenCLSerialBatches))] + public void SetupKerneliumOpenCLSerialBatches() => PrepareBatches(ComputeBackend.OpenCL, KerneliumOpenCLSerialBatches); + + [GlobalSetup(Target = nameof(KerneliumOpenCLAsyncBatches))] + public void SetupKerneliumOpenCLAsyncBatches() => PrepareBatches(ComputeBackend.OpenCL, () => KerneliumOpenCLAsyncBatches().GetAwaiter().GetResult()); + + [GlobalSetup(Target = nameof(KerneliumOpenCLThreadedAsyncBatches))] + public void SetupKerneliumOpenCLThreadedAsyncBatches() => PrepareBatches(ComputeBackend.OpenCL, KerneliumOpenCLThreadedAsyncBatches, threaded: true); + + [GlobalSetup(Target = nameof(KerneliumCudaSerialBatches))] + public void SetupKerneliumCudaSerialBatches() => PrepareBatches(ComputeBackend.Cuda, KerneliumCudaSerialBatches); + + [GlobalSetup(Target = nameof(KerneliumCudaAsyncBatches))] + public void SetupKerneliumCudaAsyncBatches() => PrepareBatches(ComputeBackend.Cuda, () => KerneliumCudaAsyncBatches().GetAwaiter().GetResult()); + + [GlobalSetup(Target = nameof(KerneliumCudaThreadedAsyncBatches))] + public void SetupKerneliumCudaThreadedAsyncBatches() => PrepareBatches(ComputeBackend.Cuda, KerneliumCudaThreadedAsyncBatches, threaded: true); + + [Benchmark] + public void KerneliumCpuSerialBatches() => RunSerialBatches(); + + [Benchmark] + public Task KerneliumCpuAsyncBatches() => RunAsyncBatches(); + + [Benchmark] + public void KerneliumCpuThreadedAsyncBatches() => RunThreadedBatches(); + + [Benchmark] + public void KerneliumOpenCLSerialBatches() => RunSerialBatches(); + + [Benchmark] + public Task KerneliumOpenCLAsyncBatches() => RunAsyncBatches(); + + [Benchmark] + public void KerneliumOpenCLThreadedAsyncBatches() => RunThreadedBatches(); + + [Benchmark] + public void KerneliumCudaSerialBatches() => RunSerialBatches(); + + [Benchmark] + public Task KerneliumCudaAsyncBatches() => RunAsyncBatches(); + + [Benchmark] + public void KerneliumCudaThreadedAsyncBatches() => RunThreadedBatches(); + + [GlobalSetup(Target = nameof(KerneliumCudaSerialBatchesLaunchOnly))] + public void SetupKerneliumCudaSerialBatchesLaunchOnly() => + PrepareCudaBatchLaunches(KerneliumCudaSerialBatchesLaunchOnly); + + [GlobalSetup(Target = nameof(KerneliumCudaAsyncBatchesLaunchOnly))] + public void SetupKerneliumCudaAsyncBatchesLaunchOnly() => + PrepareCudaBatchLaunches(() => KerneliumCudaAsyncBatchesLaunchOnly().GetAwaiter().GetResult()); + + [Benchmark] + public void KerneliumCudaSerialBatchesLaunchOnly() => LaunchSerialBatches(); + + [Benchmark] + public Task KerneliumCudaAsyncBatchesLaunchOnly() => LaunchAsyncBatches(); + + private void PrepareCudaBatchLaunches(Action launch) => + PrepareBatches(ComputeBackend.Cuda, () => + { + launch(); + DownloadBatches(); + }); + + private void PrepareBatches(ComputeBackend hardware, Action benchmark, bool threaded = false) => + Prepare(benchmark, () => + { + var gpu = Own(new GPU(new() { ComputeBackend = hardware })); + Console.WriteLine($"Kernelium device: {gpu.Device.Name} ({gpu.Device.AcceleratorType})"); + var kernel = Workload == ComputeWorkload.VectorAdd + ? gpu.CreateKernel(AddKernel) + : gpu.CreateKernel(MandelbrotBatchKernel); + + batches = new KerneliumBatch[BatchCount]; + for (int i = 0; i < batches.Length; i++) + { + int start = i * elementCount / batches.Length; + int end = (i + 1) * elementCount / batches.Length; + int length = end - start; + var output = Own(gpu.Allocate(length)); + var hostResult = new int[length]; + object[] parameters = Workload == ComputeWorkload.VectorAdd + ? [Own(gpu.Upload(left[start..end])), Own(gpu.Upload(right[start..end])), output] + : [sideShift, start, output]; + batches[i] = new KerneliumBatch( + () => kernel.Execute(length, parameters), + () => kernel.ExecuteAsync(length, parameters), + () => output.Download(hostResult), + hostResult + ); + } + + if (threaded) + submissionWorkers = new NativeThreads(BatchCount, BatchCount, (index, _) => SubmitBatch(index)); + }, usesBatches: true); + + private void RunSerialBatches() + { + LaunchSerialBatches(); + DownloadBatches(); + } + + private async Task RunAsyncBatches() + { + await LaunchAsyncBatches().ConfigureAwait(false); + DownloadBatches(); + } + + private void LaunchSerialBatches() + { + foreach (var batch in batches!) + batch.Execute(); + } + + private Task LaunchAsyncBatches() => + Task.WhenAll(batches![0].ExecuteAsync(), batches[1].ExecuteAsync()); + + private void RunThreadedBatches() + { + submissionWorkers!.Run(); + foreach (var error in submissionErrors) + { + if (error is not null) + throw new AggregateException(submissionErrors.OfType()); + } + DownloadBatches(); + } + + private void SubmitBatch(int index) + { + try + { + batches![index].ExecuteAsync().GetAwaiter().GetResult(); + } + catch (Exception error) + { + submissionErrors[index] = error; + } + } + + private void DownloadBatches() + { + foreach (var batch in batches!) + batch.Download(); + } +} diff --git a/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Device.cs b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Device.cs new file mode 100644 index 0000000..cf4cb63 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.Device.cs @@ -0,0 +1,158 @@ +using BenchmarkDotNet.Attributes; +using ILGPU; +using ILGPU.Runtime; +using ILGPU.Runtime.CPU; +using ILGPU.Runtime.Cuda; +using ILGPU.Runtime.OpenCL; +using Kernelium; +using Kernelium.Enums; + +public partial class ComputeBenchmarks +{ + private Action launchDevice = null!; + private Action downloadDevice = null!; + + [GlobalSetup(Target = nameof(KerneliumCpu))] + public void SetupKerneliumCpu() => Prepare(KerneliumCpu, () => PrepareKernelium(ComputeBackend.Cpu)); + + [GlobalSetup(Target = nameof(KerneliumOpenCL))] + public void SetupKerneliumOpenCL() => Prepare(KerneliumOpenCL, () => PrepareKernelium(ComputeBackend.OpenCL)); + + [GlobalSetup(Target = nameof(KerneliumCuda))] + public void SetupKerneliumCuda() => Prepare(KerneliumCuda, () => PrepareKernelium(ComputeBackend.Cuda)); + + [GlobalSetup(Target = nameof(RawIlgpuCpu))] + public void SetupRawIlgpuCpu() => Prepare(RawIlgpuCpu, () => PrepareRawIlgpu(ComputeBackend.Cpu)); + + [GlobalSetup(Target = nameof(RawIlgpuOpenCL))] + public void SetupRawIlgpuOpenCL() => Prepare(RawIlgpuOpenCL, () => PrepareRawIlgpu(ComputeBackend.OpenCL)); + + [GlobalSetup(Target = nameof(RawIlgpuCuda))] + public void SetupRawIlgpuCuda() => Prepare(RawIlgpuCuda, () => PrepareRawIlgpu(ComputeBackend.Cuda)); + + [Benchmark] + public void KerneliumCpu() => RunDevice(); + + [Benchmark] + public void KerneliumOpenCL() => RunDevice(); + + [Benchmark] + public void KerneliumCuda() => RunDevice(); + + [Benchmark] + public void RawIlgpuCpu() => RunDevice(); + + [Benchmark] + public void RawIlgpuOpenCL() => RunDevice(); + + [Benchmark] + public void RawIlgpuCuda() => RunDevice(); + + [GlobalSetup(Target = nameof(KerneliumCudaLaunchOnly))] + public void SetupKerneliumCudaLaunchOnly() => Prepare(RunDevice, () => PrepareKernelium(ComputeBackend.Cuda)); + + [GlobalSetup(Target = nameof(KerneliumCudaDownloadOnly))] + public void SetupKerneliumCudaDownloadOnly() => Prepare(RunDevice, () => PrepareKernelium(ComputeBackend.Cuda)); + + [GlobalSetup(Target = nameof(RawIlgpuCudaLaunchOnly))] + public void SetupRawIlgpuCudaLaunchOnly() => Prepare(RunDevice, () => PrepareRawIlgpu(ComputeBackend.Cuda)); + + [GlobalSetup(Target = nameof(RawIlgpuCudaDownloadOnly))] + public void SetupRawIlgpuCudaDownloadOnly() => Prepare(RunDevice, () => PrepareRawIlgpu(ComputeBackend.Cuda)); + + [Benchmark] + public void KerneliumCudaLaunchOnly() => launchDevice(); + + [Benchmark] + public void KerneliumCudaDownloadOnly() => downloadDevice(); + + [Benchmark] + public void RawIlgpuCudaLaunchOnly() => launchDevice(); + + [Benchmark] + public void RawIlgpuCudaDownloadOnly() => downloadDevice(); + + private void PrepareKernelium(ComputeBackend hardware) + { + var gpu = Own(new GPU(new() { ComputeBackend = hardware })); + var output = Own(gpu.Allocate(elementCount)); + Console.WriteLine($"Kernelium device: {gpu.Device.Name} ({gpu.Device.AcceleratorType})"); + + if (Workload == ComputeWorkload.VectorAdd) + { + var inputLeft = Own(gpu.Upload(left)); + var inputRight = Own(gpu.Upload(right)); + var add = gpu.CreateKernel(AddKernel); + launchDevice = () => add.Execute(elementCount, inputLeft, inputRight, output); + } + else + { + var render = gpu.CreateKernel(MandelbrotKernel); + launchDevice = () => render.Execute(elementCount, sideShift, output); + } + downloadDevice = () => output.Download(result); + } + + private void PrepareRawIlgpu(ComputeBackend hardware) + { + var context = Own(Context.CreateDefault()); + var accelerator = Own(hardware switch + { + ComputeBackend.Cpu => (Accelerator)context.CreateCPUAccelerator(0), + ComputeBackend.OpenCL => context.CreateCLAccelerator(0), + ComputeBackend.Cuda => context.CreateCudaAccelerator(0), + _ => throw new ArgumentOutOfRangeException(nameof(hardware)) + }); + Console.WriteLine($"Raw ILGPU device: {accelerator.Name} ({accelerator.AcceleratorType})"); + + var output = Own(accelerator.Allocate1D(elementCount)); + ArrayView outputView = output.View; + var stream = accelerator.DefaultStream; + Action launch; + if (Workload == ComputeWorkload.VectorAdd) + { + var inputLeft = Own(accelerator.Allocate1D(elementCount)); + var inputRight = Own(accelerator.Allocate1D(elementCount)); + inputLeft.CopyFromCPU(left); + inputRight.CopyFromCPU(right); + ArrayView leftView = inputLeft.View; + ArrayView rightView = inputRight.View; + + var code = AddKernel; + var kernel = accelerator.LoadKernel(code.Method); + var config = GetLaunchConfig(accelerator, kernel); + var add = kernel.CreateLauncherDelegate< + Action, ArrayView, ArrayView>>(); + launch = () => add(stream, config, leftView, rightView, outputView); + } + else + { + var code = MandelbrotKernel; + var kernel = accelerator.LoadKernel(code.Method); + var config = GetLaunchConfig(accelerator, kernel); + var render = kernel.CreateLauncherDelegate< + Action>>(); + launch = () => render(stream, config, sideShift, outputView); + } + + launchDevice = () => + { + launch(); + accelerator.Synchronize(); + }; + downloadDevice = () => output.CopyToCPU(result); + } + + private void RunDevice() + { + launchDevice(); + downloadDevice(); + } + + private KernelConfig GetLaunchConfig(Accelerator accelerator, ILGPU.Runtime.Kernel kernel) + { + int threads = accelerator.EstimateGroupSize(kernel); + int blocks = (int)((elementCount + (long)threads - 1) / threads); + return new KernelConfig(blocks, threads); + } +} diff --git a/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.cs b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.cs new file mode 100644 index 0000000..09ced41 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/ComputeBenchmarks.cs @@ -0,0 +1,189 @@ +using System.Numerics; +using BenchmarkDotNet.Attributes; +using ILGPU; + +public enum ComputeWorkload +{ + VectorAdd, + Mandelbrot +} + +[MemoryDiagnoser] +public partial class ComputeBenchmarks +{ + private int elementCount; + private int sideShift; + + private int[] left = null!; + private int[] right = null!; + private int[] result = null!; + private Action computeRange = null!; + private NativeThreads? workers; + private readonly List deviceResources = new(); + + [Params(256, 1024, 4096)] + public int Side { get; set; } + + [Params(ComputeWorkload.VectorAdd, ComputeWorkload.Mandelbrot)] + public ComputeWorkload Workload { get; set; } + + [GlobalSetup(Target = nameof(CSharpSingleThread))] + public void SetupSingleThread() => Prepare(CSharpSingleThread); + + [GlobalSetup(Target = nameof(CSharpNativeThreads))] + public void SetupNativeThreads() => Prepare(CSharpNativeThreads, useNativeThreads: true); + + [Benchmark(Baseline = true)] + public void CSharpSingleThread() => computeRange(0, elementCount, result); + + [Benchmark] + public void CSharpNativeThreads() => workers!.Run(); + + private void Prepare(Action benchmark, Action? prepareDevice = null, bool useNativeThreads = false, bool usesBatches = false) + { + elementCount = Side * Side; + if (!usesBatches) + { + result = new int[elementCount]; + Array.Fill(result, int.MinValue); + } + + if (Workload == ComputeWorkload.VectorAdd) + { + left = new int[elementCount]; + right = new int[elementCount]; + for (int i = 0; i < elementCount; i++) + { + left[i] = i % 127 - 63; + right[i] = i % 61 - 30; + } + + computeRange = AddRange; + } + else + { + sideShift = BitOperations.Log2((uint)Side); + computeRange = MandelbrotRange; + } + + try + { + if (useNativeThreads) + { + int threadCount = Math.Min(Environment.ProcessorCount, elementCount); + workers = new NativeThreads(threadCount, elementCount, (start, end) => computeRange(start, end, result)); + Console.WriteLine($"Dedicated C# workers: {threadCount}"); + } + + prepareDevice?.Invoke(); + + var expected = new int[elementCount]; + computeRange(0, elementCount, expected); + benchmark(); + if (!MatchesExpected(expected)) + throw new InvalidOperationException($"Incorrect output for {Workload}."); + } + catch + { + Cleanup(); + throw; + } + } + + private bool MatchesExpected(int[] expected) + { + if (batches is null) + return result.AsSpan().SequenceEqual(expected); + + int start = 0; + foreach (var batch in batches) + { + if (!batch.Result.AsSpan().SequenceEqual(expected.AsSpan(start, batch.Result.Length))) + return false; + start += batch.Result.Length; + } + + return true; + } + + private T Own(T resource) where T : IDisposable + { + deviceResources.Add(resource); + return resource; + } + + [GlobalCleanup] + public void Cleanup() + { + workers?.Dispose(); + submissionWorkers?.Dispose(); + for (int i = deviceResources.Count - 1; i >= 0; i--) + deviceResources[i].Dispose(); + deviceResources.Clear(); + } + + private void AddRange(int start, int end, int[] output) + { + for (int i = start; i < end; i++) + output[i] = left[i] + right[i]; + } + + private void MandelbrotRange(int start, int end, int[] output) + { + int shift = sideShift; + for (int i = start; i < end; i++) + output[i] = EscapeIterations(i, shift); + } + + private static void AddKernel(ArrayView a, ArrayView b, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + output[index] = a[index] + b[index]; + } + + private static void MandelbrotKernel(int shift, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + output[index] = EscapeIterations(index, shift); + } + + private static void MandelbrotBatchKernel(int shift, int start, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + output[index] = EscapeIterations(start + index, shift); + } + + private static int EscapeIterations(int index, int shift) + { + const int scale = 4096; + const int escapeRadiusSquared = 4 * scale * scale; + const int maxIterations = 256; + + int x = index & ((1 << shift) - 1); + int y = index >> shift; + int real = ((3 * scale * x) >> shift) - 2 * scale; + int imaginary = ((3 * scale * y) >> shift) - 3 * scale / 2; + int zr = 0; + int zi = 0; + + for (int iteration = 0; iteration < maxIterations; iteration++) + { + int realSquared = zr * zr; + int imaginarySquared = zi * zi; + if (realSquared + imaginarySquared > escapeRadiusSquared) + return iteration; + + zi = DivideByScale(2 * zr * zi) + imaginary; + zr = DivideByScale(realSquared - imaginarySquared) + real; + } + + return maxIterations; + } + + // Use identical fixed-point rounding on the host and in the kernel. + private static int DivideByScale(int value) => + (value + ((value >> 31) & 4095)) >> 12; +} diff --git a/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.csproj b/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.csproj new file mode 100644 index 0000000..a29732c --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.csproj @@ -0,0 +1,14 @@ + + + Exe + false + net10.0 + enable + enable + + + + + + + diff --git a/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.slnx b/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.slnx new file mode 100644 index 0000000..b319411 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/Kernelium.Benchmarks.slnx @@ -0,0 +1,4 @@ + + + + diff --git a/benchmarks/Kernelium.Benchmarks/NativeThreads.cs b/benchmarks/Kernelium.Benchmarks/NativeThreads.cs new file mode 100644 index 0000000..e247917 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/NativeThreads.cs @@ -0,0 +1,72 @@ +internal sealed class NativeThreads : IDisposable +{ + private readonly Barrier barrier = new(1); + private readonly List threads = new(); + private bool stopping; + + public NativeThreads(int count, int length, Action computeRange) + { + try + { + for (int i = 0; i < count; i++) + { + int start = (int)((long)i * length / count); + int end = (int)((long)(i + 1) * length / count); + var thread = new Thread(() => Work(computeRange, start, end)) + { + IsBackground = true + }; + + barrier.AddParticipant(); + try + { + thread.Start(); + } + catch + { + barrier.RemoveParticipant(); + throw; + } + + threads.Add(thread); + } + } + catch + { + Dispose(); + throw; + } + } + + public void Run() + { + barrier.SignalAndWait(); + barrier.SignalAndWait(); + } + + private void Work(Action computeRange, int start, int end) + { + while (true) + { + barrier.SignalAndWait(); + if (stopping) + return; + + computeRange(start, end); + barrier.SignalAndWait(); + } + } + + public void Dispose() + { + if (stopping) + return; + + stopping = true; + barrier.SignalAndWait(); + foreach (var thread in threads) + thread.Join(); + + barrier.Dispose(); + } +} diff --git a/benchmarks/Kernelium.Benchmarks/Program.cs b/benchmarks/Kernelium.Benchmarks/Program.cs new file mode 100644 index 0000000..973e3d1 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/Program.cs @@ -0,0 +1,129 @@ +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Filters; +using BenchmarkDotNet.Running; +using ILGPU; +using ILGPU.Runtime; +using ILGPU.Runtime.OpenCL; + +bool interactive = args.Length == 0 && !Console.IsInputRedirected && !Console.IsOutputRedirected; +try +{ +#if DEBUG + Console.Error.WriteLine("BenchmarkDotNet requires a Release build."); + Console.Error.WriteLine("In Visual Studio, select Release and run without debugging (Ctrl+F5)."); + return 1; +#else + bool cudaRecheck = args is ["--cuda-recheck"]; + bool cudaBreakdown = args is ["--cuda-breakdown"]; + bool cudaAsyncThroughput = args is ["--cuda-async-throughput"]; + bool gpuOnly = args is ["--gpu-only", ..]; + using var context = Context.CreateDefault(); + bool hasCuda = context.Devices.Any(device => device.AcceleratorType == AcceleratorType.Cuda); + var openClDevice = context.Devices.OfType().FirstOrDefault(); + bool hasOpenCl = openClDevice is not null; + bool hasOpenClGpu = openClDevice?.DeviceType.HasFlag(CLDeviceType.CL_DEVICE_TYPE_GPU) == true; + + if (!hasCuda) + Console.WriteLine("CUDA unavailable. Its benchmarks will be skipped."); + if (!hasOpenCl) + Console.WriteLine("OpenCL unavailable. Its benchmarks will be skipped."); + + var config = ManualConfig.Create(DefaultConfig.Instance) + .AddEventProcessor(new BenchmarkProgress()) + .AddFilter(new SimpleFilter(benchmark => benchmark.Descriptor.WorkloadMethod.Name switch + { + var name when name.StartsWith(nameof(ComputeBenchmarks.KerneliumCuda), StringComparison.Ordinal) + || name == nameof(ComputeBenchmarks.RawIlgpuCuda) => hasCuda, + var name when name.StartsWith(nameof(ComputeBenchmarks.KerneliumOpenCL), StringComparison.Ordinal) + || name == nameof(ComputeBenchmarks.RawIlgpuOpenCL) => gpuOnly ? hasOpenClGpu : hasOpenCl, + _ => !gpuOnly + })); + + config.AddFilter(new SimpleFilter(benchmark => IsCudaBreakdown(benchmark.Descriptor.WorkloadMethod.Name) + == cudaBreakdown)); + config.AddFilter(new SimpleFilter(benchmark => IsCudaAsyncThroughput(benchmark.Descriptor.WorkloadMethod.Name) + == cudaAsyncThroughput)); + + if (gpuOnly) + { + if (hasOpenCl && !hasOpenClGpu) + Console.WriteLine("OpenCL device 0 is not a GPU. Its benchmarks will be skipped."); + if (!hasCuda && !hasOpenClGpu) + return 1; + + var options = args.Skip(1).ToList(); + if (!options.Any(option => option is "--filter" or "-f" || option.StartsWith("--filter=", StringComparison.Ordinal))) + options.AddRange(["--filter", "*"]); + if (!options.Any(option => option is "--artifacts" or "-a" || option.StartsWith("--artifacts=", StringComparison.Ordinal))) + options.AddRange(["--artifacts", "BenchmarkDotNet.Artifacts/GpuOnly"]); + args = options.ToArray(); + } + + if (cudaRecheck || cudaBreakdown) + { + if (!hasCuda) + return 1; + + config.AddFilter(new SimpleFilter(benchmark => + (cudaBreakdown || benchmark.Descriptor.WorkloadMethod.Name == nameof(ComputeBenchmarks.KerneliumCuda)) + && benchmark.Parameters.Items.Any(parameter => + parameter.Name == nameof(ComputeBenchmarks.Side) && parameter.Value is 4096))); + args = + [ + "--filter", "*", + "--launchCount", "3", + "--warmupCount", "4", + "--iterationCount", "20", + "--invocationCount", "4", + "--unrollFactor", "1", + "--artifacts", cudaBreakdown ? "BenchmarkDotNet.Artifacts/CudaBreakdown" : "BenchmarkDotNet.Artifacts/CudaRecheck" + ]; + } + + if (cudaAsyncThroughput) + { + if (!hasCuda) + return 1; + + config.AddFilter(new SimpleFilter(benchmark => benchmark.Parameters.Items.Any(parameter => + parameter.Name == nameof(ComputeBenchmarks.Side) && parameter.Value is 256 or 4096))); + args = + [ + "--filter", "*", + "--launchCount", "2", + "--warmupCount", "4", + "--iterationCount", "12", + "--artifacts", "BenchmarkDotNet.Artifacts/CudaAsyncThroughput" + ]; + } + + var summaries = BenchmarkSwitcher.FromAssembly(typeof(ComputeBenchmarks).Assembly).Run(args, config); + return summaries.Any(summary => summary.HasCriticalValidationErrors || + summary.Reports.Any(report => !report.Success)) ? 1 : 0; +#endif +} +catch (Exception error) +{ + Console.Error.WriteLine(error); + return 1; +} +finally +{ + if (interactive) + { + Console.WriteLine("Press any key to exit."); + Console.ReadKey(intercept: true); + } +} + +#if !DEBUG +static bool IsCudaBreakdown(string method) => method is + nameof(ComputeBenchmarks.KerneliumCudaLaunchOnly) or + nameof(ComputeBenchmarks.KerneliumCudaDownloadOnly) or + nameof(ComputeBenchmarks.RawIlgpuCudaLaunchOnly) or + nameof(ComputeBenchmarks.RawIlgpuCudaDownloadOnly); + +static bool IsCudaAsyncThroughput(string method) => method is + nameof(ComputeBenchmarks.KerneliumCudaSerialBatchesLaunchOnly) or + nameof(ComputeBenchmarks.KerneliumCudaAsyncBatchesLaunchOnly); +#endif diff --git a/benchmarks/Kernelium.Benchmarks/README.md b/benchmarks/Kernelium.Benchmarks/README.md new file mode 100644 index 0000000..8567eb8 --- /dev/null +++ b/benchmarks/Kernelium.Benchmarks/README.md @@ -0,0 +1,148 @@ +# Kernelium benchmarks + +This .NET 10 project uses BenchmarkDotNet to compare vector addition and Mandelbrot +at three sizes. It builds Kernelium from the same checkout, so each benchmark measures the +source at the checked-out commit. [Historical results](../results/2026-11-28.md) + +| Side | Elements per vector or image | +|---:|---:| +| 256 | 65,536 | +| 1,024 | 1,048,576 | +| 4,096 | 16,777,216 | + +The full suite reports a single-threaded C# baseline for each size and workload. +The 4096 × 4096 cases take longer to run and each integer array or device buffer +for a full workload at that size uses 64 MiB. Each of the two batches uses +32 MiB per integer buffer. + +## Open in Visual Studio + +Open `Kernelium.Benchmarks.slnx` to load the benchmark and the Kernelium library +together. Set `Kernelium.Benchmarks` as the startup project, select **Release**, +and start without debugging (**Ctrl+F5**). BenchmarkDotNet rejects Debug builds. + +## Run + +From the repository root, run the full suite in Release: + +```powershell +cd benchmarks/Kernelium.Benchmarks +dotnet run -c Release -- --filter "*" +``` + +BenchmarkDotNet runs warm-up and measurement iterations in separate benchmark +processes and exports results to `BenchmarkDotNet.Artifacts/results`. CUDA and +OpenCL cases run when ILGPU detects a compatible device. To check setup and +correctness quickly, add `--job Dry`. Use the full run for timing comparisons. +The console progress bar advances after each benchmark case. Its time estimate +uses completed cases and can shift as the suite reaches larger workloads. + +## What is measured + +| Case | Measured work | +|---|---| +| `CSharpSingleThread` | A plain C# loop on the benchmark thread | +| `CSharpNativeThreads` | The same loop split across dedicated `System.Threading.Thread` workers, including synchronization | +| `KerneliumCpu`, `KerneliumOpenCL`, `KerneliumCuda` | Kernel launch, synchronization, and readback into a reused host array | +| `RawIlgpuCpu`, `RawIlgpuOpenCL`, `RawIlgpuCuda` | The same kernel, synchronization, and readback using ILGPU directly | + +Raw ILGPU uses a typed launcher and decides group dimensions during setup. +Kernelium uses its public `Execute(workItems, ...)` path, which caches the +preferred group size per compiled kernel and computes the grid dimensions for +each launch. Both use the same kernels, persistent device +buffers, and device index 0. Compare rows for the same workload, size, and +backend when measuring the cost of the wrapper API. + +Workers, arrays, device buffers, and input uploads are set up before measurement. +Every case checks all results against the single-threaded C# calculation before +benchmarking. `CSharpNativeThreads` uses the logical CPU count available to the process. +BenchmarkDotNet's allocation results cover managed memory. + +## Compare async and multithreaded submission + +The batch cases split the same workload into two equal parts. Each part has its +own reusable device buffers and host output array. All three cases time both +launches and both downloads, in the same download order. Each variant uses one accelerator instance. + +| Case suffix | How the two kernels are submitted | +|---|---| +| `SerialBatches` | Two synchronous launches in sequence. Use this row as the reference for split workloads. | +| `AsyncBatches` | One host thread submits both launches and awaits them with `Task.WhenAll`. | +| `ThreadedAsyncBatches` | Two dedicated host threads each submit an async launch and wait for it. Worker synchronization is included. | + +From the benchmark project directory, run the batch comparison on available +backends or restrict it to the CPU: + +```powershell +dotnet run -c Release -- --filter "*Batches" +dotnet run -c Release -- --filter "*KerneliumCpu*Batches" +``` + +Compare the `Mean` values for the same backend, workload, and size. In the full +suite the `Ratio` column uses the single-threaded C# baseline. +Comparing `SerialBatches` with `AsyncBatches` shows the effect of async submission +for the same split. Comparing the two async rows shows the cost or benefit of +submitting from dedicated host threads. The original single-launch Kernelium +row shows the cost of running the complete workload without splitting it. +CUDA and OpenCL may overlap the kernels when the device and driver support it. +ILGPU runs one kernel at a time per CPU accelerator. + +## Recheck the two large synchronous CUDA cases + +From the benchmark project directory, run: + +```powershell +dotnet run -c Release -- --cuda-recheck +``` + +This selects only the synchronous `KerneliumCuda` VectorAdd and Mandelbrot +cases at 4096 × 4096. Each case runs in three separate processes with four warmup +iterations and 20 measured iterations per process. Each measured iteration +executes the benchmark four times, for 240 timed launch-and-download calls per +case. Review the mean, median, and standard deviation in +`BenchmarkDotNet.Artifacts/CudaRecheck/results`. + +## Diagnose CUDA launch and readback costs + +```powershell +dotnet run -c Release -- --cuda-breakdown +``` + +This compares Kernelium and raw ILGPU at 4096 × 4096 for VectorAdd and +Mandelbrot. It times launch through completion and readback from an existing +device buffer as separate benchmarks. Setup checks the full result before +either phase is measured. The eight cases use the same repetition settings +as the recheck and write to `BenchmarkDotNet.Artifacts/CudaBreakdown/results`. + +## Run the GPU cases only + +```powershell +dotnet run -c Release -- --gpu-only +``` + +This runs the Kernelium and raw ILGPU CUDA and OpenCL cases, including +Kernelium's serial and async batch variants. The sweep covers both workloads at +all three sizes. The C# and ILGPU CPU cases are excluded. OpenCL runs when the +benchmark's device at index 0 is a GPU. Reports go to +`BenchmarkDotNet.Artifacts/GpuOnly/results`. + +Add `--filter "*Batches"` after `--gpu-only` to focus on batch execution. Compare +the `Mean` column for matching cases. The single-threaded C# baseline is part of +the full suite. + +## Measure CUDA async throughput without readback + +```powershell +dotnet run -c Release -- --cuda-async-throughput +``` + +This runs eight cases covering VectorAdd and Mandelbrot at 256 × 256 and +4096 × 4096. Each operation completes the same two independent kernels using +either sequential `Execute` calls or `Task.WhenAll` over two `ExecuteAsync` +calls. Inputs and outputs stay on the device during measurement. Setup uploads +the inputs and downloads and validates the outputs from one untimed operation. + +Compare the mean and managed allocation columns for serial and async at the +same size and workload. The mean measures time to complete two kernels. Each +case uses two benchmark processes with 12 measured iterations each. Reports go +to `BenchmarkDotNet.Artifacts/CudaAsyncThroughput/results`. From 63fa51d508352c7faf7b17edc65950b94f48134c Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:05:51 +0100 Subject: [PATCH 04/11] Address Kernelium 1.0 release review findings --- Kernelium.Test/OperationSchedulerTests.cs | 24 +++++++++ Kernelium.Test/StreamWorkTests.cs | 3 -- Kernelium/Execution/OperationScheduler.cs | 22 +++++--- Kernelium/Execution/StreamWork.cs | 6 +-- Kernelium/GPU.cs | 14 +---- Kernelium/Kernelium.csproj | 2 + Kernelium/Memory/IArrayTransfers.cs | 11 ---- Kernelium/Memory/ParameterMarshaller.cs | 66 +++++------------------ README.md | 15 ++++-- llms.txt | 2 +- 10 files changed, 71 insertions(+), 94 deletions(-) delete mode 100644 Kernelium/Memory/IArrayTransfers.cs diff --git a/Kernelium.Test/OperationSchedulerTests.cs b/Kernelium.Test/OperationSchedulerTests.cs index 4d254b3..2f7cd52 100644 --- a/Kernelium.Test/OperationSchedulerTests.cs +++ b/Kernelium.Test/OperationSchedulerTests.cs @@ -116,6 +116,30 @@ public static async Task BufferCloseKeepsOwnerAliveUntilNativeReleaseCompletes() await Task.WhenAll(bufferDispose, ownerDispose).WaitAsync(TimeSpan.FromSeconds(10)); } + [Test] + public static async Task FailedOwnerCloseIsReportedToOtherDisposalCallers() + { + var owner = new Resource(); + var buffer = new Resource(); + using var use = Claim((owner, false)); + var failure = new InvalidOperationException("Cleanup failed."); + var ownerClose = Task.Run(() => Close(owner, () => throw failure)); + await WaitUntilClosed(owner); + var otherClose = Task.Run(() => Close(owner, () => Assert.Fail("Owner released twice."))); + var bufferClose = Task.Run(() => Close(buffer, () => Assert.Fail("Owner is closing."), owner)); + await WaitUntilClosed(buffer); + use.Dispose(); + + foreach (var close in new[] { ownerClose, otherClose, bufferClose }) + { + var error = Assert.ThrowsAsync(async () => + await close.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.That(error, Is.SameAs(failure)); + } + Assert.That(Assert.Throws(() => Close(buffer, + () => Assert.Fail("Buffer released twice."), owner)), Is.SameAs(failure)); + } + [Test] public static void ReservingClaimsPreventsFurtherMutationOrReuse() { diff --git a/Kernelium.Test/StreamWorkTests.cs b/Kernelium.Test/StreamWorkTests.cs index 7c87197..d38cc00 100644 --- a/Kernelium.Test/StreamWorkTests.cs +++ b/Kernelium.Test/StreamWorkTests.cs @@ -14,7 +14,6 @@ public static void FailedStreamDrainRetainsResourcesAndPreventsReuse() using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); using var stream = new FailingStream(gpu.Accelerator); using var buffer = gpu.Allocate(1); - var viewBeforeFailure = buffer.View; var retained = new ConcurrentBag(); var temporary = new TrackingResource(); var work = new StreamWork(stream, retained, [buffer.Allocation]); @@ -28,8 +27,6 @@ public static void FailedStreamDrainRetainsResourcesAndPreventsReuse() Assert.That(retained, Does.Contain(buffer.Allocation)); Assert.Throws(() => buffer.Download()); Assert.Throws(() => _ = buffer.View); - Assert.Throws(() => gpu.ConvertParameters([], [], buffer)); - Assert.Throws(() => gpu.ConvertParameters([], [], viewBeforeFailure)); } [Test] diff --git a/Kernelium/Execution/OperationScheduler.cs b/Kernelium/Execution/OperationScheduler.cs index d08dd78..ed81c60 100644 --- a/Kernelium/Execution/OperationScheduler.cs +++ b/Kernelium/Execution/OperationScheduler.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; namespace Kernelium.Execution; @@ -11,7 +12,8 @@ internal sealed class Resource { internal Task? Writer; internal readonly HashSet Readers = new(); - internal TaskCompletionSource? CloseCompletion; + // Store the outcome so a failed close can be replayed without an unobserved task fault. + internal TaskCompletionSource? CloseCompletion; internal volatile bool UnsafeToUse; internal void ThrowIfUnsafe() @@ -122,15 +124,16 @@ internal static bool IsClosed(Resource resource) internal static void Close(Resource resource, Action release, Resource? owner = null) { - Task wait; - TaskCompletionSource? closeCompletion = null; + Task wait = Task.CompletedTask; + TaskCompletionSource? closeCompletion = null; + Task? priorClose = null; Reservation? ownerUse = null; Action? releaseAfterWait = null; lock (admission) { if (resource.CloseCompletion is { } existing) { - wait = existing.Task; + priorClose = existing.Task; } else { @@ -139,7 +142,7 @@ internal static void Close(Resource resource, Action release, Resource? owner = wait = Task.WhenAll(resource.Readers.Append(resource.Writer ?? Task.CompletedTask)); if (owner?.CloseCompletion is { } ownerClosed) { - wait = Task.WhenAll(wait, ownerClosed.Task); + priorClose = ownerClosed.Task; releaseAfterWait = null; } else if (owner is not null) @@ -149,15 +152,22 @@ internal static void Close(Resource resource, Action release, Resource? owner = } } + ExceptionDispatchInfo? failure = null; try { wait.GetAwaiter().GetResult(); + priorClose?.GetAwaiter().GetResult()?.Throw(); releaseAfterWait?.Invoke(); } + catch (Exception error) when (closeCompletion is not null) + { + failure = ExceptionDispatchInfo.Capture(error); + throw; + } finally { ownerUse?.Dispose(); - closeCompletion?.SetResult(); + closeCompletion?.SetResult(failure); } } } diff --git a/Kernelium/Execution/StreamWork.cs b/Kernelium/Execution/StreamWork.cs index 6df3652..e0e6475 100644 --- a/Kernelium/Execution/StreamWork.cs +++ b/Kernelium/Execution/StreamWork.cs @@ -2,7 +2,6 @@ using System.Runtime.ExceptionServices; using ILGPU; using ILGPU.Runtime; -using Kernelium.Memory; namespace Kernelium.Execution; @@ -10,7 +9,7 @@ internal sealed class StreamWork( AcceleratorStream stream, ConcurrentBag retained, MemoryBuffer[] allocations, - CudaStagingPool? cudaStaging = null) : IArrayTransfers + CudaStagingPool? cudaStaging = null) { private readonly List temporary = new(); private readonly List held = new(); @@ -53,7 +52,8 @@ internal void Upload(ArrayView view, T[] data) where T : unmanaged } } - void IArrayTransfers.TransferArray(MemoryBuffer1D buffer, T[] data, bool copyIn, bool copyOut) + internal void TransferArray(MemoryBuffer1D buffer, T[] data, bool copyIn, bool copyOut) + where T : unmanaged { Own(buffer); ArrayView view = buffer.View; diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index dfffd63..c2f0261 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -17,7 +17,6 @@ public class GPU : IDisposable private readonly Accelerator accelerator; private readonly KernelCompiler compiler; private readonly KernelExecutor executor; - private readonly ParameterMarshaller marshaller; private readonly DeviceOperations operations; /// Information and capabilities for the selected device. @@ -46,7 +45,7 @@ public GPU(GPUConfiguration? config = null) }; operations = new DeviceOperations(accelerator, stagingBudget, config.BufferTransferDiagnostics); compiler = new KernelCompiler(accelerator); - marshaller = new ParameterMarshaller(accelerator); + var marshaller = new ParameterMarshaller(accelerator); executor = new KernelExecutor( accelerator, compiler, @@ -158,17 +157,6 @@ private static void Validate2DExtent(int width, int height) ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); } - public object[] ConvertParameters( - List buffers, - List copyBack, - params object[] parameters) - { - return marshaller.ConvertParameters( - buffers, - copyBack, - parameters - ); - } /// Allocates a device buffer initialized to zero. public GPUBuffer Allocate(int length) where T : unmanaged => CreateBuffer(length, null); diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index d913d03..93d9c8f 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -6,6 +6,8 @@ enable true true + true + $(NoWarn);CS1591 Kernelium 1.0.0 Raphael Hinterdorfer diff --git a/Kernelium/Memory/IArrayTransfers.cs b/Kernelium/Memory/IArrayTransfers.cs deleted file mode 100644 index a01fd61..0000000 --- a/Kernelium/Memory/IArrayTransfers.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ILGPU; -using ILGPU.Runtime; - -namespace Kernelium.Memory; - -internal interface IArrayTransfers -{ - // Takes ownership of the allocation before starting any transfers. - void TransferArray(MemoryBuffer1D buffer, T[] data, - bool copyIn, bool copyOut) where T : unmanaged; -} diff --git a/Kernelium/Memory/ParameterMarshaller.cs b/Kernelium/Memory/ParameterMarshaller.cs index dea9fae..3489b7b 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -10,6 +10,10 @@ internal sealed class ParameterMarshaller { private readonly Accelerator accelerator; private static readonly ConditionalWeakTable viewFields = new(); + private static readonly ConditionalWeakTable arrayMarshallers = new(); + + private delegate object ArrayMarshaller(ParameterMarshaller marshaller, StreamWork work, + Array data, bool copyIn, bool copyOut); private static readonly MethodInfo marshalArrayMethod = typeof(ParameterMarshaller).GetMethod( @@ -23,41 +27,15 @@ public ParameterMarshaller(Accelerator accelerator) this.accelerator = accelerator; } - public object[] ConvertParameters( - List buffers, - List copyBack, - params object[] parameters) + internal void MarshalForLaunch(StreamWork work, object[] parameters) { - ArgumentNullException.ThrowIfNull(buffers); - ArgumentNullException.ThrowIfNull(copyBack); - ArgumentNullException.ThrowIfNull(parameters); - var result = new object[parameters.Length]; - ConvertParameters(parameters, result, new CallerArrayTransfers(buffers, copyBack), validateViews: true); - return result; - } - - internal void MarshalForLaunch(StreamWork work, object[] capturedParameters) => - ConvertParameters(capturedParameters, capturedParameters, work, validateViews: false); - - private void ConvertParameters(object[] parameters, object[] result, IArrayTransfers transfers, bool validateViews) - { - for (int i = 0; i < parameters.Length; i++) { object parameter = parameters[i]; - ArgumentNullException.ThrowIfNull(parameter); - if (parameter is IGPUBuffer gpuBuffer) - parameter = gpuBuffer.GetView(); - var arrayArgument = parameter as ArrayArgument; if ((arrayArgument?.Data ?? parameter) is not Array array) - { - if (validateViews) - VisitViews(parameter, i, null); - result[i] = parameter; continue; - } Type elementType = array.GetType().GetElementType()!; if (array.GetType() != elementType.MakeArrayType()) @@ -65,13 +43,13 @@ private void ConvertParameters(object[] parameters, object[] result, IArrayTrans bool copyIn = arrayArgument is null || arrayArgument.IsInput; bool copyOut = arrayArgument is null || !arrayArgument.IsInput; - result[i] = marshalArrayMethod - .MakeGenericMethod(elementType) - .Invoke(this, new object[] { transfers, array, copyIn, copyOut })!; + var marshal = arrayMarshallers.GetValue(elementType, static type => + marshalArrayMethod.MakeGenericMethod(type).CreateDelegate()); + parameters[i] = marshal(this, work, array, copyIn, copyOut); } } - private void VisitViews(object value, int parameterIndex, Action? visit) + private void VisitViews(object value, int parameterIndex, Action visit) { if (value is IArrayView view) { @@ -83,10 +61,7 @@ private void VisitViews(object value, int parameterIndex, Action? throw new ArgumentException( $"Kernel parameter {parameterIndex} contains a view from a different accelerator.", "parameters"); - if (visit is null) - OperationScheduler.For(buffer).ThrowIfUnsafe(); - else - visit(buffer); + visit(buffer); return; } @@ -133,25 +108,12 @@ private static bool MayContainView(Type type) => typeof(IArrayView).IsAssignableFrom(type) || (type.IsValueType && !type.IsPrimitive && !type.IsEnum); - private ArrayView MarshalArray( - IArrayTransfers transfers, T[] data, bool copyIn, bool copyOut) where T : unmanaged + private object MarshalArray( + StreamWork work, Array data, bool copyIn, bool copyOut) where T : unmanaged { var buffer = accelerator.Allocate1D(data.Length); - transfers.TransferArray(buffer, data, copyIn, copyOut); - return buffer.View; - } - - private sealed class CallerArrayTransfers(List buffers, List copyBack) : IArrayTransfers - { - public void TransferArray(MemoryBuffer1D buffer, T[] data, - bool copyIn, bool copyOut) where T : unmanaged - { - buffers.Add(buffer); - if (copyIn) - buffer.CopyFromCPU(data); - if (copyOut) - copyBack.Add(() => buffer.CopyToCPU(data)); - } + work.TransferArray(buffer, (T[])data, copyIn, copyOut); + return (ArrayView)buffer.View; } } } diff --git a/README.md b/README.md index 64ffa5a..9863e05 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,10 @@ directions, and reusable device buffers. For 1.0.0, use the preview names `GenerateKernel` and `HardwareType`. The preview names remain available as obsolete aliases. +If you used `GPU.ConvertParameters` in a preview, pass arguments directly to +`Execute` or `ExecuteAsync` for Kernelium-managed transfers. For direct ILGPU +launches, pass device views such as `GPUBuffer.View` to the ILGPU launcher. + Use `CreateTypedKernel` for compile-time argument checks, `GPUConfiguration.CudaPinnedStagingCacheBytes` to tune CUDA staging, and `GPUConfiguration.ExecutionDiagnostics` to observe launches. @@ -144,9 +148,9 @@ 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`. Synchronous Kernelium operations use and wait for the accelerator's default stream. -Async launches use Kernelium-owned streams on CUDA and OpenCL. Coordinate dependencies -across streams and keep resources alive when using direct ILGPU calls or -`gpu.ConvertParameters`, which are outside Kernelium's operation tracking. +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. #### CreateKernel @@ -197,7 +201,8 @@ gpu.ClearKernelCache(); #### Dispose Closes the GPU to new work, waits for accepted work including queued launches, then -releases the accelerator and its associated resources. Repeated disposal is safe. +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. @@ -383,7 +388,7 @@ 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. Repeated disposal is safe. +buffer. Concurrent and repeated disposal calls report the same cleanup outcome. ### Check kernel arguments at compile time diff --git a/llms.txt b/llms.txt index a9c88bd..f3d8108 100644 --- a/llms.txt +++ b/llms.txt @@ -79,7 +79,7 @@ await Task.WhenAll( - `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. Synchronous operations use and wait for the default stream. For direct ILGPU work and the low-level `ConvertParameters` API, coordinate cross-stream dependencies and resource lifetimes yourself. +- Pass compatible ILGPU views from the same accelerator to Kernelium. Synchronous operations use and wait for the default stream. For direct ILGPU launches, coordinate cross-stream dependencies and keep the GPU and any buffers or views alive until the work completes. ## Benchmarks From c85db1a3959c37bfde979c2c30d20cfed02d050a Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:10:40 +0100 Subject: [PATCH 05/11] Finalize Kernelium 1.0 release settings --- .github/workflows/nuget.yml | 11 ++++++++++- Kernelium/DataTypes/GPUConfiguration.cs | 2 +- README.md | 2 +- llms.txt | 2 +- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index b6e0685..6623e0c 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -5,6 +5,7 @@ on: push: branches: - main + - develop tags: - 'v*' @@ -39,7 +40,15 @@ jobs: 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" + if [[ "$version" == *-* ]]; then + echo "package=$version" >> "$GITHUB_OUTPUT" + else + project_version=$(dotnet msbuild Kernelium/Kernelium.csproj -p:Configuration=Release -getProperty:PackageVersion) + if [[ "$version" != "$project_version" ]]; then + echo "::error::Stable tag $TAG must match the project package version $project_version." + exit 1 + fi + fi - run: dotnet restore Kernelium.slnx - name: Run tests run: dotnet test Kernelium.slnx -c Release --no-restore diff --git a/Kernelium/DataTypes/GPUConfiguration.cs b/Kernelium/DataTypes/GPUConfiguration.cs index b8067ca..d874c6f 100644 --- a/Kernelium/DataTypes/GPUConfiguration.cs +++ b/Kernelium/DataTypes/GPUConfiguration.cs @@ -16,7 +16,7 @@ public HardwareType HardwareType public int DeviceIndex { get; set; } /// Total CUDA pinned staging cache budget in bytes for this GPU. Zero disables caching. - public long CudaPinnedStagingCacheBytes { get; set; } = 384L * 1024 * 1024; + public long CudaPinnedStagingCacheBytes { get; set; } = 128L * 1024 * 1024; /// Optional callback invoked after a kernel execution completes or fails. public Action? ExecutionDiagnostics { get; set; } diff --git a/README.md b/README.md index 9863e05..54c5c10 100644 --- a/README.md +++ b/README.md @@ -303,7 +303,7 @@ kernel uses. ILGPU runs one kernel at a time per CPU accelerator. ### Configure CUDA pinned staging -CUDA caches up to 384 MiB of pinned host staging per `GPU` instance by +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. diff --git a/llms.txt b/llms.txt index f3d8108..c6fee76 100644 --- a/llms.txt +++ b/llms.txt @@ -63,7 +63,7 @@ await Task.WhenAll( - Host-array arguments must be one-dimensional `T[]` arrays with unmanaged elements. Flatten 2D data before passing it. 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` or `ExecuteAsync` and call `destination.Download(output)` when the host needs the result. -- On CUDA, `GPUConfiguration.CudaPinnedStagingCacheBytes` defaults to 384 MiB total, shared among the default stream and two async streams. Set it to `0` to disable caching. Transfers that exceed the available cache use temporary pinned staging. On Windows and Linux, explicit buffer downloads copy directly into the destination array. +- On CUDA, `GPUConfiguration.CudaPinnedStagingCacheBytes` defaults to 128 MiB total, shared among the default stream and two async streams. Set it to `0` to disable caching. Transfers that exceed the available cache use temporary pinned staging. On Windows and Linux, explicit buffer downloads copy directly into the destination array. - Use buffers with the GPU that created them. Keep intermediate results on the device across launches and download explicitly. Buffer and GPU disposal reject new operations, drain accepted operations including queued uses, and release resources. Repeated disposal is safe. If a driver failure leaves retained work with unknown completion at teardown, disposal throws and preserves the affected resources until process exit. ## Typed launches and diagnostics From 175d501195ef2db685852265f0444e5965d5b3a1 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:17:37 +0100 Subject: [PATCH 06/11] Validate kernel launches and accelerator lifetime --- Kernelium.Test/DeviceOperationsTests.cs | 2 ++ Kernelium.Test/TypedKernelTests.cs | 38 +++++++++++++++++++++++++ Kernelium/DataTypes/GPUConfiguration.cs | 1 + Kernelium/Execution/DeviceOperations.cs | 6 ++++ Kernelium/Execution/KernelExecutor.cs | 38 ++++++++++++++++++++----- Kernelium/Execution/LaunchSizing.cs | 4 +-- Kernelium/GPU.cs | 3 ++ Kernelium/Kernel.cs | 3 +- Kernelium/Memory/ParameterMarshaller.cs | 2 -- README.md | 3 +- 10 files changed, 87 insertions(+), 13 deletions(-) diff --git a/Kernelium.Test/DeviceOperationsTests.cs b/Kernelium.Test/DeviceOperationsTests.cs index 91d316b..34c2d73 100644 --- a/Kernelium.Test/DeviceOperationsTests.cs +++ b/Kernelium.Test/DeviceOperationsTests.cs @@ -20,6 +20,8 @@ public static void AsyncCpuWorkRejectsAnUnsafeDefaultStream() _ => Assert.Fail("Work reached an unsafe stream."))); Assert.That(error!.Message, Does.Contain("could not establish stream completion")); + Assert.Throws(() => operations.UseAccelerator(() => + throw new AssertionException("Compilation reached an unsafe stream."))); } [TestCase(true)] diff --git a/Kernelium.Test/TypedKernelTests.cs b/Kernelium.Test/TypedKernelTests.cs index b8c9df0..3d8d058 100644 --- a/Kernelium.Test/TypedKernelTests.cs +++ b/Kernelium.Test/TypedKernelTests.cs @@ -2,11 +2,49 @@ using ILGPU; using Kernelium.DataTypes; using Kernelium.Enums; +using Kernelium.Execution; namespace Kernelium.Test; internal static class TypedKernelTests { + [Test] + public static void UntypedLaunchRejectsIncorrectScalarAndArrayTypesBeforeCompilation() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(Add, CompilationStrategy.Lazy); + var scalar = Assert.Throws(() => kernel.Execute(1, 1L, new int[1], new int[1])); + var array = Assert.ThrowsAsync(() => + kernel.ExecuteAsync(1, 1, ArrayArgument.Input(new long[1]), new int[1])); + + Assert.That(scalar!.Message, Does.Contain("'offset'").And.Contain("System.Int64")); + Assert.That(array!.Message, Does.Contain("'input'").And.Contain("System.Int64[]")); + Assert.That(kernel.IsCompiled, Is.False); + } + + [TestCase(13, 4, 3)] + [TestCase(int.MaxValue, 3, int.MaxValue)] + public static void LaunchSizingRejectsGridAndPaddedIndexOverflow(int workItems, int groupSize, int gridLimit) + { + var error = Assert.Throws(() => + LaunchSizing.GetBlockCount(workItems, groupSize, gridLimit, nameof(workItems))); + Assert.That(error!.ParamName, Is.EqualTo(nameof(workItems))); + } + + [Test] + public static void DisposedGpuRejectsCompilationAndCacheAccess() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var kernel = gpu.CreateKernel(Add, CompilationStrategy.Lazy); + gpu.Dispose(); + + Assert.Throws(() => gpu.CreateKernel(Add, CompilationStrategy.Lazy)); + Assert.Throws(() => new Kernel(gpu, Add)); + Assert.Throws(() => gpu.IsCompiled(Add)); + Assert.Throws(gpu.ClearKernelCache); + Assert.Throws(kernel.Compile); + } + [Test] public static async Task TypedLaunchesAcceptScalarsAndArrayAdapters() { diff --git a/Kernelium/DataTypes/GPUConfiguration.cs b/Kernelium/DataTypes/GPUConfiguration.cs index d874c6f..e429037 100644 --- a/Kernelium/DataTypes/GPUConfiguration.cs +++ b/Kernelium/DataTypes/GPUConfiguration.cs @@ -13,6 +13,7 @@ public HardwareType HardwareType set => ComputeBackend = (ComputeBackend)value; } + /// Index within the explicitly selected backend. Auto selects its own device. public int DeviceIndex { get; set; } /// Total CUDA pinned staging cache budget in bytes for this GPU. Zero disables caching. diff --git a/Kernelium/Execution/DeviceOperations.cs b/Kernelium/Execution/DeviceOperations.cs index 1a85279..3ac5165 100644 --- a/Kernelium/Execution/DeviceOperations.cs +++ b/Kernelium/Execution/DeviceOperations.cs @@ -186,9 +186,15 @@ internal TResult ObserveTransfer(int length, bool upload, Func(Func action) { using var reservation = OperationScheduler.Reserve(GetClaims(useDefaultStream: false)); + reservation.Predecessors.GetAwaiter().GetResult(); + reservation.CheckResources(); + using var binding = accelerator.BindScoped(); return action(); } + internal void ThrowIfDisposed() => ObjectDisposedException.ThrowIf( + OperationScheduler.IsClosed(Lifetime) || accelerator.IsDisposed, nameof(GPU)); + internal void Dispose(Action tearDown) { OperationScheduler.Close(Lifetime, () => diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index 7fbb418..e072599 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Reflection; using ILGPU; using ILGPU.Runtime; using Kernelium.Compilation; @@ -108,13 +109,20 @@ private void Report(Delegate kernel, bool isAsync, ExecutionMeasurement? measure private (object[] Parameters, OperationScheduler.Claims Claims, MemoryBuffer[] Allocations) Capture( Delegate kernel, object[] parameters, bool useDefaultStream) { - ValidateArguments(kernel, parameters); + ArgumentNullException.ThrowIfNull(parameters); + var signature = kernel.Method.GetParameters(); + if (parameters.Length != signature.Length) + throw new ArgumentException( + $"Kernel expects {signature.Length} parameters, but {parameters.Length} were provided.", + nameof(parameters)); // Always capture into a real object array. A covariant params array // can reject the views that replace its original entries. var captured = new object[parameters.Length]; parameters.CopyTo(captured, 0); var claims = operations.GetClaims(useDefaultStream); - return (captured, claims, marshaller.Capture(captured, claims)); + var allocations = marshaller.Capture(captured, claims); + ValidateArgumentTypes(signature, captured); + return (captured, claims, allocations); } private void Launch(Kernel kernel, Func getConfig, @@ -150,14 +158,30 @@ private void Launch(Kernel kernel, Func getC } } - private static void ValidateArguments(Delegate kernel, object[] parameters) + private static void ValidateArgumentTypes(ParameterInfo[] signature, object[] parameters) { - ArgumentNullException.ThrowIfNull(parameters); - int expected = kernel.Method.GetParameters().Length; - if (parameters.Length != expected) + for (int i = 0; i < parameters.Length; i++) + { + Type expected = signature[i].ParameterType; + object argument = parameters[i] is ArrayArgument adapter ? adapter.Data : parameters[i]; + Type actual = argument.GetType(); + if (argument is Array) + { + if (!actual.IsSZArray) + throw new NotSupportedException("Only one-dimensional arrays are supported."); + if (expected.IsConstructedGenericType && expected.GetGenericTypeDefinition() == typeof(ArrayView<>) && + expected.GetGenericArguments()[0] == actual.GetElementType()) + continue; + } + else if (expected.IsAssignableFrom(actual)) + { + continue; + } + throw new ArgumentException( - $"Kernel expects {expected} parameters, but {parameters.Length} were provided.", + $"Kernel parameter {i + 1} ('{signature[i].Name}') expects {expected}, but received {actual}.", nameof(parameters)); + } } } } diff --git a/Kernelium/Execution/LaunchSizing.cs b/Kernelium/Execution/LaunchSizing.cs index ee239b1..695967c 100644 --- a/Kernelium/Execution/LaunchSizing.cs +++ b/Kernelium/Execution/LaunchSizing.cs @@ -22,7 +22,7 @@ internal LaunchSizing(Accelerator accelerator) internal KernelConfig For1D(CompiledKernel compiled, int workItems) { int threads = groupSizes.GetValue(compiled, estimateGroupSize).Threads; - int blocks = DivideRoundUp(workItems, threads); + int blocks = GetBlockCount(workItems, threads, accelerator.MaxGridSize.X, nameof(workItems)); return new KernelConfig(blocks, threads); } @@ -62,7 +62,7 @@ internal KernelConfig For2D(CompiledKernel compiled, int width, int height) return new KernelConfig(grid, group); } - private static int GetBlockCount(int length, int groupSize, int gridLimit, string parameterName) + internal static int GetBlockCount(int length, int groupSize, int gridLimit, string parameterName) { int groups = DivideRoundUp(length, groupSize); if (groups > gridLimit || (long)groups * groupSize - 1 > int.MaxValue) diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index c2f0261..fd95d5e 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -123,12 +123,15 @@ internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) } public bool IsCompiled(Delegate kernel) { + ThrowIfDisposed(); return compiler.IsCompiled(kernel); } public void ClearKernelCache() { + ThrowIfDisposed(); compiler.Clear(); } + internal void ThrowIfDisposed() => operations.ThrowIfDisposed(); internal void Execute(Kernel kernel, KernelConfig config, object[] parameters) => executor.Execute(kernel, _ => config, parameters); diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index fe75a46..658adda 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -18,6 +18,7 @@ public Kernel(GPU gpu, Delegate method) : this(gpu, method, CompilationStrategy. internal Kernel(GPU gpu, Delegate method, CompilationStrategy strategy) { ArgumentNullException.ThrowIfNull(gpu); + gpu.ThrowIfDisposed(); if (!Enum.IsDefined(strategy)) throw new ArgumentOutOfRangeException(nameof(strategy)); KernelCompiler.ValidateKernel(method); @@ -46,4 +47,4 @@ public Task Execute2DAsync(int width, int height, params object[] parameters) => GPU.Execute2DAsync(this, width, height, parameters); } -} \ No newline at end of file +} diff --git a/Kernelium/Memory/ParameterMarshaller.cs b/Kernelium/Memory/ParameterMarshaller.cs index 3489b7b..b1d2141 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -38,8 +38,6 @@ internal void MarshalForLaunch(StreamWork work, object[] parameters) 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; diff --git a/README.md b/README.md index 54c5c10..7b8b8d9 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,8 @@ bool compiled = gpu.IsCompiled(VectorAdd); #### ClearKernelCache -Clears Kernelium's internal kernel cache. +Removes cached entries so future launches can compile them again. In-flight +launches retain their compiled kernels until their work completes. ```csharp gpu.ClearKernelCache(); From f1e070f748702a2c2610b1629e2cc569f5e06f5a Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:25:31 +0100 Subject: [PATCH 07/11] Document the Kernelium 1.0 public API --- Kernelium/ArrayArgument.cs | 8 + Kernelium/DataTypes/GPUConfiguration.cs | 6 + Kernelium/Enums/ComputeBackend.cs | 4 + Kernelium/Enums/HardwareType.cs | 5 + Kernelium/GPU.cs | 196 ++++++++++++- Kernelium/Kernel.cs | 78 ++++- Kernelium/KernelArgument.cs | 23 +- Kernelium/Kernelium.csproj | 1 - Kernelium/Memory/GPUBuffer.cs | 22 ++ Kernelium/TypedKernel.cs | 364 ++++++++++++++++++++++++ Kernelium/TypedKernelExtensions.cs | 126 ++++++++ 11 files changed, 824 insertions(+), 9 deletions(-) diff --git a/Kernelium/ArrayArgument.cs b/Kernelium/ArrayArgument.cs index bcb8f90..f44e540 100644 --- a/Kernelium/ArrayArgument.cs +++ b/Kernelium/ArrayArgument.cs @@ -14,6 +14,10 @@ private ArrayArgument(Array data, bool isInput) } /// Uploads the array and leaves its host contents unchanged after execution. + /// The unmanaged element type. + /// The host source array. Keep it available until execution completes. + /// An argument for an array-view parameter. + /// is null. public static ArrayArgument Input(T[] array) where T : unmanaged => new(array, isInput: true); @@ -21,6 +25,10 @@ public static ArrayArgument Input(T[] array) where T : unmanaged => /// Downloads the result into the array after execution. The kernel must /// initialize every element because the original contents are not uploaded. /// + /// The unmanaged element type. + /// The host destination array. Keep it available until execution completes. + /// An argument for an array-view parameter. + /// is null. public static ArrayArgument Output(T[] array) where T : unmanaged => new(array, isInput: false); } diff --git a/Kernelium/DataTypes/GPUConfiguration.cs b/Kernelium/DataTypes/GPUConfiguration.cs index e429037..0f777a6 100644 --- a/Kernelium/DataTypes/GPUConfiguration.cs +++ b/Kernelium/DataTypes/GPUConfiguration.cs @@ -2,10 +2,13 @@ namespace Kernelium.DataTypes; +/// Configures device selection, CUDA staging, and diagnostics for a GPU instance. public class GPUConfiguration { + /// The backend to use. The default is automatic device selection. public ComputeBackend ComputeBackend { get; set; } = ComputeBackend.Auto; + /// Compatibility alias for . [Obsolete("Use ComputeBackend instead.")] public HardwareType HardwareType { @@ -17,11 +20,14 @@ public HardwareType HardwareType public int DeviceIndex { get; set; } /// Total CUDA pinned staging cache budget in bytes for this GPU. Zero disables caching. + /// The default is 128 MiB, allocated on demand and shared across streams. Transfers can use temporary pinned memory beyond the cache budget. public long CudaPinnedStagingCacheBytes { get; set; } = 128L * 1024 * 1024; /// Optional callback invoked after a kernel execution completes or fails. + /// Calls can overlap when operations are concurrent. Kernelium ignores exceptions thrown by the callback. public Action? ExecutionDiagnostics { get; set; } /// Optional callback for explicit buffer uploads and downloads. + /// Calls can overlap when operations are concurrent. Kernelium ignores exceptions thrown by the callback. public Action? BufferTransferDiagnostics { get; set; } } diff --git a/Kernelium/Enums/ComputeBackend.cs b/Kernelium/Enums/ComputeBackend.cs index c4860f5..6b4bdb9 100644 --- a/Kernelium/Enums/ComputeBackend.cs +++ b/Kernelium/Enums/ComputeBackend.cs @@ -3,8 +3,12 @@ namespace Kernelium.Enums; /// Selects the execution backend used by a GPU instance. public enum ComputeBackend { + /// Use an OpenCL device and its compatible runtime. OpenCL, + /// Use an NVIDIA device and its CUDA driver. Cuda, + /// Use the ILGPU CPU accelerator. Cpu, + /// Let ILGPU select the preferred available device. Auto } diff --git a/Kernelium/Enums/HardwareType.cs b/Kernelium/Enums/HardwareType.cs index 5f772f5..6b2cd25 100644 --- a/Kernelium/Enums/HardwareType.cs +++ b/Kernelium/Enums/HardwareType.cs @@ -4,12 +4,17 @@ namespace Kernelium.Enums { + /// Compatibility names for . [Obsolete("Use ComputeBackend instead.")] public enum HardwareType { + /// Use an OpenCL device and its compatible runtime. OpenCL, + /// Use an NVIDIA device and its CUDA driver. Cuda, + /// Use the ILGPU CPU accelerator. Cpu, + /// Let ILGPU select the preferred available device. Auto } } diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index fd95d5e..ff7dbd5 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -11,6 +11,12 @@ namespace Kernelium { + /// Owns an ILGPU accelerator and schedules Kernelium work on it. + /// + /// Kernelium coordinates concurrent launches and transfers that share tracked resources. + /// Callers must coordinate direct ILGPU commands and host-side access to arrays in use by a launch. + /// Dispose this instance when its kernels and buffers are no longer needed. + /// public class GPU : IDisposable { private readonly Context context; @@ -23,9 +29,13 @@ public class GPU : IDisposable public Device Device => accelerator.Device; /// The ILGPU accelerator owned by this GPU instance. - /// Dispose this GPU instance to release the accelerator. + /// Keep this GPU alive while issuing direct ILGPU commands. The GPU owns disposal of the accelerator. public Accelerator Accelerator => accelerator; + /// Creates a GPU instance with its own ILGPU context and accelerator. + /// Device and execution settings. Null uses the default configuration. + /// The CUDA staging cache budget is negative. + /// The configured backend value is undefined. public GPU(GPUConfiguration? config = null) { config ??= new GPUConfiguration(); @@ -60,10 +70,19 @@ public GPU(GPUConfiguration? config = null) throw; } } + /// [Obsolete("Use CreateKernel instead.")] public Kernel GenerateKernel(Delegate kernel, bool precompile = true) => CreateKernel(kernel, precompile); + /// Creates a reusable kernel whose arguments are checked at launch. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast, captures state, or returns a value. + /// is undefined. + /// This GPU has been disposed. public Kernel CreateKernel(Delegate kernel, CompilationStrategy strategy = CompilationStrategy.Eager) { var instance = new Kernel(this, kernel, strategy); @@ -72,48 +91,202 @@ public Kernel CreateKernel(Delegate kernel, CompilationStrategy strategy = Compi return instance; } + /// Creates a reusable kernel whose arguments are checked at launch. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast, captures state, or returns a value. + /// This GPU has been disposed. public Kernel CreateKernel(Delegate kernel, bool precompile) => CreateKernel(kernel, precompile ? CompilationStrategy.Eager : CompilationStrategy.Lazy); + /// Creates a reusable kernel with typed arguments. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// Type of kernel parameter 6. + /// A static method or a noncapturing lambda supported by ILGPU. + /// When to compile the kernel. The default is eager compilation. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// is undefined. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); + /// Creates a reusable kernel with typed arguments. + /// Type of kernel parameter 1. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// Type of kernel parameter 6. + /// A static method or a noncapturing lambda supported by ILGPU. + /// True to compile during creation. False to compile on first launch. + /// A kernel associated with this GPU. + /// is null. + /// The delegate is multicast or captures state. + /// The owning GPU has been disposed. public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => new(CreateKernel(kernel, precompile)); @@ -121,11 +294,18 @@ internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) { return operations.UseAccelerator(() => compiler.GetOrCompile(kernel)); } + /// Checks whether the compiled kernel method is currently cached on this GPU. + /// The delegate identifying the kernel method. + /// True if the method has a compiled cache entry. + /// This GPU has been disposed. public bool IsCompiled(Delegate kernel) { ThrowIfDisposed(); return compiler.IsCompiled(kernel); } + /// Removes compiled kernel entries from this GPU's cache. + /// In-flight launches retain their compiled kernels. Manual kernels need an explicit compile before a later launch unless their method is already cached. + /// This GPU has been disposed. public void ClearKernelCache() { ThrowIfDisposed(); @@ -161,9 +341,21 @@ private static void Validate2DExtent(int width, int height) } /// Allocates a device buffer initialized to zero. + /// The unmanaged element type. + /// The positive number of elements. + /// A buffer the caller should dispose. It belongs to this GPU. + /// is nonpositive. + /// This GPU has been disposed. public GPUBuffer Allocate(int length) where T : unmanaged => CreateBuffer(length, null); + /// Allocates a device buffer and copies a host array into it before returning. + /// The unmanaged element type. + /// The nonempty source array. + /// A buffer the caller should dispose. It belongs to this GPU. + /// is null. + /// is empty. + /// This GPU has been disposed. public GPUBuffer Upload(T[] data) where T : unmanaged { ArgumentNullException.ThrowIfNull(data); @@ -190,6 +382,8 @@ private GPUBuffer CreateBuffer(int length, T[]? data) where T : unmanaged }); } + /// Stops accepting new work, waits for accepted work, and releases accelerator resources. + /// Concurrent and repeated calls report the same cleanup outcome. Driver failures can prevent release when native work cannot safely be confirmed complete. public void Dispose() => operations.Dispose(() => { try diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index 658adda..87d63dc 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -4,13 +4,31 @@ namespace Kernelium { + /// A reusable kernel associated with a single GPU. + /// + /// Match argument types to the kernel signature. Pass a one-dimensional host array, an + /// adapter, or a device buffer for an parameter. + /// Plain host arrays are uploaded and copied back. Keep arrays and buffers available until the + /// launch completes, and coordinate direct ILGPU work separately from Kernelium scheduling. + /// Automatic sizing can pad the workload. Guard accesses against the logical dimensions. + /// public class Kernel { + /// The delegate identifying the kernel method. public Delegate Method { get; } + /// The GPU that owns this kernel's accelerator and compiled cache. public GPU GPU { get; } + /// Gets whether this method currently has a compiled entry in the owning GPU's cache. + /// The owning GPU has been disposed. public bool IsCompiled => GPU.IsCompiled(Method); internal CompilationStrategy Strategy { get; } + /// Creates a kernel that compiles on first launch or on an explicit compile call. + /// The GPU that will compile and execute this kernel. + /// A static method or a noncapturing lambda supported by ILGPU. + /// or is null. + /// The delegate is multicast, captures state, or returns a value. + /// The owning GPU has been disposed. public Kernel(GPU gpu, Delegate method) : this(gpu, method, CompilationStrategy.Lazy) { } @@ -26,23 +44,71 @@ internal Kernel(GPU gpu, Delegate method, CompilationStrategy strategy) GPU = gpu; Method = method; } + /// Compiles the kernel for its GPU or reuses an existing compiled entry. + /// The owning GPU has been disposed. public void Compile() => GPU.GetOrCompile(Method); + + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// The arguments in kernel signature order. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public void Execute(KernelConfig config, params object[] parameters) => GPU.Execute(this, config, parameters); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. + /// The arguments in kernel signature order. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public void Execute(int workItems, params object[] parameters) => GPU.Execute(this, workItems, parameters); - /// Launches a two-dimensional workload with an automatically sized group. - /// Guard both global indices against the logical width and height. + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. + /// The arguments in kernel signature order. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public void Execute2D(int width, int height, params object[] parameters) => GPU.Execute2D(this, width, height, parameters); - /// Submits a one-dimensional workload and completes after host copy-back. + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. + /// The arguments in kernel signature order. + /// A task that completes after execution and any requested host copy-back. Launch failures fault the task. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public Task ExecuteAsync(int workItems, params object[] parameters) => GPU.ExecuteAsync(this, workItems, parameters); - /// Submits a workload with explicit grid and group dimensions. + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// The arguments in kernel signature order. + /// A task that completes after execution and any requested host copy-back. Launch failures fault the task. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public Task ExecuteAsync(KernelConfig config, params object[] parameters) => GPU.ExecuteAsync(this, config, parameters); - /// Submits a two-dimensional workload with an automatically sized group. - /// Guard both global indices against the logical width and height. + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. + /// The arguments in kernel signature order. + /// A task that completes after execution and any requested host copy-back. Launch failures fault the task. + /// The argument array or one of its entries is null. + /// An argument has the wrong type, belongs to a different accelerator, or the argument count is incorrect. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The kernel uses manual compilation and has no cached entry, or a resource is unsafe after an earlier failure. + /// The owning GPU or a supplied buffer has been disposed. public Task Execute2DAsync(int width, int height, params object[] parameters) => GPU.Execute2DAsync(this, width, height, parameters); diff --git a/Kernelium/KernelArgument.cs b/Kernelium/KernelArgument.cs index 4384aa6..34a385c 100644 --- a/Kernelium/KernelArgument.cs +++ b/Kernelium/KernelArgument.cs @@ -4,6 +4,7 @@ namespace Kernelium; /// An argument for a kernel parameter of type . +/// A parameter type supported by ILGPU on the selected accelerator, such as a supported scalar, unmanaged value type, or array view. public readonly struct KernelArgument { private readonly object? value; @@ -14,6 +15,9 @@ public readonly struct KernelArgument // validated by the same launch pipeline as an untyped null argument. internal object Value => value ?? (object)default(T)!; + /// Wraps a scalar, value type, or device view for a typed launch. + /// The value to pass to the kernel. + /// The corresponding typed argument. public static implicit operator KernelArgument(T value) => new(value); } @@ -21,21 +25,38 @@ public readonly struct KernelArgument public static class KernelArgument { /// Uploads the array and copies it back after a successful launch. + /// The unmanaged element type. + /// The host array to upload and update. + /// An argument for an array-view parameter. + /// is null. public static KernelArgument> ReadWrite(T[] array) where T : unmanaged { ArgumentNullException.ThrowIfNull(array); return new(array); } - /// Uploads the array before launch. + /// Uploads the array before launch and leaves the host copy unchanged. + /// The unmanaged element type. + /// The host input array. + /// An argument for an array-view parameter. + /// is null. public static KernelArgument> Input(T[] array) where T : unmanaged => new(ArrayArgument.Input(array)); /// Copies the array back after a successful launch. + /// The host data is not uploaded. The kernel must initialize every element to be read back. + /// The unmanaged element type. + /// The host destination array. + /// An argument for an array-view parameter. + /// is null. public static KernelArgument> Output(T[] array) where T : unmanaged => new(ArrayArgument.Output(array)); /// Passes an existing device allocation to the kernel. + /// The unmanaged element type. + /// The buffer owned by the kernel's GPU. Keep it alive through completion. + /// An argument that borrows the device allocation. + /// is null. public static KernelArgument> Buffer(GPUBuffer buffer) where T : unmanaged { ArgumentNullException.ThrowIfNull(buffer); diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index 93d9c8f..ccae929 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -7,7 +7,6 @@ true true true - $(NoWarn);CS1591 Kernelium 1.0.0 Raphael Hinterdorfer diff --git a/Kernelium/Memory/GPUBuffer.cs b/Kernelium/Memory/GPUBuffer.cs index 91923b9..4b8f5c7 100644 --- a/Kernelium/Memory/GPUBuffer.cs +++ b/Kernelium/Memory/GPUBuffer.cs @@ -4,6 +4,9 @@ namespace Kernelium.Memory { + /// An owned device allocation that can be reused across kernel launches. + /// The unmanaged element type. + /// Use this buffer with the GPU that created it. Dispose it when no longer needed. Coordinate direct ILGPU access separately from Kernelium launches and transfers. public sealed class GPUBuffer : IDisposable, IGPUBuffer where T : unmanaged { private readonly MemoryBuffer1D buffer; @@ -13,9 +16,13 @@ public sealed class GPUBuffer : IDisposable, IGPUBuffer where T : unmanaged internal ArrayView NativeView { get; } internal MemoryBuffer Allocation { get; } + /// The element count of the allocation. public long Length => buffer.Length; /// Gets a view that is valid for the lifetime of the buffer. + /// The view borrows the allocation. Keep this buffer and its owning GPU alive until work using the view completes. + /// The buffer or its owning GPU has been disposed. + /// The allocation is unsafe after an earlier failure. public ArrayView View { get @@ -40,12 +47,20 @@ internal GPUBuffer(Accelerator accelerator, DeviceOperations operations, int len IArrayView IGPUBuffer.GetView() => View; + /// Copies a host array into the existing allocation and waits for the transfer. + /// The source array. Its length must equal . + /// is null. + /// The source length differs from the buffer length. + /// The buffer or its owning GPU has been disposed. public void Upload(T[] data) { ArgumentNullException.ThrowIfNull(data); operations.ObserveTransfer(data.Length, upload: true, () => Transfer(data, upload: true)); } + /// Copies the allocation to a new host array and waits for the transfer. + /// An independent array containing all buffer elements. + /// The buffer or its owning GPU has been disposed. public T[] Download() { return operations.ObserveTransfer(checked((int)Length), upload: false, () => @@ -57,6 +72,11 @@ public T[] Download() }); } + /// Copies the allocation to an existing host array and waits for the transfer. + /// The destination array. Its length must equal . + /// is null. + /// The destination length differs from the buffer length. + /// The buffer or its owning GPU has been disposed. public void Download(T[] destination) { ArgumentNullException.ThrowIfNull(destination); @@ -88,6 +108,8 @@ private void ThrowIfDisposed() => OperationScheduler.IsClosed(lifetime) || OperationScheduler.IsClosed(operations.Lifetime) || buffer.IsDisposed || buffer.Accelerator.IsDisposed, this); + /// Closes the buffer to new work and waits for accepted uses before releasing the allocation. + /// Concurrent and repeated calls report the same cleanup outcome. The GPU retains allocations that cannot safely be released. public void Dispose() => OperationScheduler.Close(lifetime, () => { if (!lifetime.UnsafeToUse) diff --git a/Kernelium/TypedKernel.cs b/Kernelium/TypedKernel.cs index 0330525..0aa81f4 100644 --- a/Kernelium/TypedKernel.cs +++ b/Kernelium/TypedKernel.cs @@ -3,211 +3,575 @@ namespace Kernelium; /// A kernel with no launch arguments. +/// A reusable typed kernel with no parameters. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems) => kernel.Execute(workItems); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// The owning GPU has been disposed. public void Execute(KernelConfig config) => kernel.Execute(config); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height) => kernel.Execute2D(width, height); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems) => kernel.ExecuteAsync(workItems); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config) => kernel.ExecuteAsync(config); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height) => kernel.Execute2DAsync(width, height); } /// A kernel with 1 statically typed launch argument. +/// A reusable typed kernel with 1 parameter. +/// Type of kernel parameter 1. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1) => kernel.Execute(workItems, argument1.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1) => kernel.Execute(config, argument1.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1) => kernel.Execute2D(width, height, argument1.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1) => kernel.ExecuteAsync(workItems, argument1.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1) => kernel.ExecuteAsync(config, argument1.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1) => kernel.Execute2DAsync(width, height, argument1.Value); } /// A kernel with 2 statically typed launch arguments. +/// A reusable typed kernel with 2 parameters. +/// Type of kernel parameter 1. +/// Type of kernel parameter 2. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2) => kernel.Execute(workItems, argument1.Value, argument2.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2) => kernel.Execute(config, argument1.Value, argument2.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2) => kernel.Execute2D(width, height, argument1.Value, argument2.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2) => kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2) => kernel.ExecuteAsync(config, argument1.Value, argument2.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2) => kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value); } /// A kernel with 3 statically typed launch arguments. +/// A reusable typed kernel with 3 parameters. +/// Type of kernel parameter 1. +/// Type of kernel parameter 2. +/// Type of kernel parameter 3. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value); } /// A kernel with 4 statically typed launch arguments. +/// A reusable typed kernel with 4 parameters. +/// Type of kernel parameter 1. +/// Type of kernel parameter 2. +/// Type of kernel parameter 3. +/// Type of kernel parameter 4. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value); } /// A kernel with 5 statically typed launch arguments. +/// A reusable typed kernel with 5 parameters. +/// Type of kernel parameter 1. +/// Type of kernel parameter 2. +/// Type of kernel parameter 3. +/// Type of kernel parameter 4. +/// Type of kernel parameter 5. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); } /// A kernel with 6 statically typed launch arguments. +/// A reusable typed kernel with 6 parameters. +/// Type of kernel parameter 1. +/// Type of kernel parameter 2. +/// Type of kernel parameter 3. +/// Type of kernel parameter 4. +/// Type of kernel parameter 5. +/// Type of kernel parameter 6. +/// See for launch and resource lifetime rules. public sealed class TypedKernel { private readonly Kernel kernel; internal TypedKernel(Kernel kernel) => this.kernel = kernel; + /// public bool IsCompiled => kernel.IsCompiled; + /// public void Compile() => kernel.Compile(); + /// Runs the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.Execute(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + /// Runs the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// The owning GPU has been disposed. public void Execute(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.Execute(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + /// Runs the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public void Execute2D(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.Execute2D(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + /// Submits the kernel over a one-dimensional workload. + /// The positive logical item count. Guard indices against this count after rounding. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task ExecuteAsync(int workItems, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.ExecuteAsync(workItems, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + /// Submits the kernel with explicit grid and group dimensions. + /// The grid and thread group dimensions. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A task that completes after execution and any requested host copy-back. + /// The owning GPU has been disposed. public Task ExecuteAsync(KernelConfig config, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.ExecuteAsync(config, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); + /// Submits the kernel over a two-dimensional workload. + /// The positive logical width. + /// The positive logical height. Guard both indices against the logical extent. + /// Argument for kernel parameter 1. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public Task Execute2DAsync(int width, int height, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5, KernelArgument argument6) => kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value, argument6.Value); } diff --git a/Kernelium/TypedKernelExtensions.cs b/Kernelium/TypedKernelExtensions.cs index d2e5eee..c1581b4 100644 --- a/Kernelium/TypedKernelExtensions.cs +++ b/Kernelium/TypedKernelExtensions.cs @@ -5,50 +5,176 @@ namespace Kernelium; /// Launches typed 2D kernels that receive their logical extent as a first parameter. public static class TypedKernelExtensions { + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent) => kernel.Execute2D(extent.X, extent.Y, extent); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent) => kernel.Execute2DAsync(extent.X, extent.Y, extent); + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent, KernelArgument argument1) => kernel.Execute2D(extent.X, extent.Y, extent, argument1); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent, KernelArgument argument1) => kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1); + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2) => kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2) => kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2); + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3); + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + /// Runs a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// Type of kernel parameter 6. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); + /// Submits a 2D launch and passes the logical extent as the first kernel argument. + /// Type of kernel parameter 2. + /// Type of kernel parameter 3. + /// Type of kernel parameter 4. + /// Type of kernel parameter 5. + /// Type of kernel parameter 6. + /// The typed kernel to launch. + /// The positive logical dimensions. Guard both global indices against this extent. + /// Argument for kernel parameter 2. + /// Argument for kernel parameter 3. + /// Argument for kernel parameter 4. + /// Argument for kernel parameter 5. + /// Argument for kernel parameter 6. + /// A task that completes after execution and any requested host copy-back. + /// A logical dimension is nonpositive or exceeds supported launch limits. + /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); From 483972d2942edb2d3f7ce9acbfba12a40b52534b Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:31:20 +0100 Subject: [PATCH 08/11] Update Actions runtimes and fix typed kernel summaries --- .github/workflows/nuget.yml | 10 +++++----- Kernelium/TypedKernel.cs | 7 ------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/.github/workflows/nuget.yml b/.github/workflows/nuget.yml index 6623e0c..3d91807 100644 --- a/.github/workflows/nuget.yml +++ b/.github/workflows/nuget.yml @@ -16,7 +16,7 @@ jobs: verify: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 0 - name: Require release commit on main @@ -26,7 +26,7 @@ jobs: echo "::error::Release tags must point to a commit on main." exit 1 fi - - uses: actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v5 with: dotnet-version: '10.0.x' - name: Resolve package version @@ -62,7 +62,7 @@ jobs: fi dotnet pack Kernelium/Kernelium.csproj -c Release --no-restore \ --output artifacts "${pack_args[@]}" - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v6 with: name: nuget-packages path: artifacts/ @@ -75,10 +75,10 @@ jobs: permissions: id-token: write steps: - - uses: actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v5 with: dotnet-version: '10.0.x' - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v7 with: name: nuget-packages path: artifacts diff --git a/Kernelium/TypedKernel.cs b/Kernelium/TypedKernel.cs index 0aa81f4..5243bf7 100644 --- a/Kernelium/TypedKernel.cs +++ b/Kernelium/TypedKernel.cs @@ -2,7 +2,6 @@ namespace Kernelium; -/// A kernel with no launch arguments. /// A reusable typed kernel with no parameters. /// See for launch and resource lifetime rules. public sealed class TypedKernel @@ -63,7 +62,6 @@ public Task Execute2DAsync(int width, int height) => kernel.Execute2DAsync(width, height); } -/// A kernel with 1 statically typed launch argument. /// A reusable typed kernel with 1 parameter. /// Type of kernel parameter 1. /// See for launch and resource lifetime rules. @@ -131,7 +129,6 @@ public Task Execute2DAsync(int width, int height, KernelArgument argument1) kernel.Execute2DAsync(width, height, argument1.Value); } -/// A kernel with 2 statically typed launch arguments. /// A reusable typed kernel with 2 parameters. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -206,7 +203,6 @@ public Task Execute2DAsync(int width, int height, KernelArgument argument1, kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value); } -/// A kernel with 3 statically typed launch arguments. /// A reusable typed kernel with 3 parameters. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -288,7 +284,6 @@ public Task Execute2DAsync(int width, int height, KernelArgument argument1, kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value); } -/// A kernel with 4 statically typed launch arguments. /// A reusable typed kernel with 4 parameters. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -377,7 +372,6 @@ public Task Execute2DAsync(int width, int height, KernelArgument argument1, kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value); } -/// A kernel with 5 statically typed launch arguments. /// A reusable typed kernel with 5 parameters. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -473,7 +467,6 @@ public Task Execute2DAsync(int width, int height, KernelArgument argument1, kernel.Execute2DAsync(width, height, argument1.Value, argument2.Value, argument3.Value, argument4.Value, argument5.Value); } -/// A kernel with 6 statically typed launch arguments. /// A reusable typed kernel with 6 parameters. /// Type of kernel parameter 1. /// Type of kernel parameter 2. From dbad7e378e1b2c0d1f1e1cf8a154da3d16852ad3 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:35:48 +0100 Subject: [PATCH 09/11] Validate null kernel arguments --- Kernelium.Test/TypedKernelTests.cs | 25 +++++++++ Kernelium/GPU.cs | 2 + Kernelium/TypedKernelExtensions.cs | 84 +++++++++++++++++++++++------- 3 files changed, 93 insertions(+), 18 deletions(-) diff --git a/Kernelium.Test/TypedKernelTests.cs b/Kernelium.Test/TypedKernelTests.cs index 3d8d058..78832c7 100644 --- a/Kernelium.Test/TypedKernelTests.cs +++ b/Kernelium.Test/TypedKernelTests.cs @@ -8,6 +8,31 @@ namespace Kernelium.Test; internal static class TypedKernelTests { + [Test] + public static void IsCompiledRejectsNullDelegate() + { + using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); + var error = Assert.Throws(() => gpu.IsCompiled(null!)); + Assert.That(error!.ParamName, Is.EqualTo("kernel")); + } + + [Test] + public static void TypedExtentExtensionsRejectNullReceivers() + { + TypedKernel kernel = null!; + TypedKernel kernelWithArguments = null!; + var extent = new Index2D(1, 1); + + Assert.That(Assert.Throws(() => kernel.Execute2D(extent))!.ParamName, + Is.EqualTo("kernel")); + Assert.That(Assert.Throws(() => kernel.Execute2DAsync(extent))!.ParamName, + Is.EqualTo("kernel")); + Assert.That(Assert.Throws(() => kernelWithArguments.Execute2D(extent, 1, 2, 3, 4, 5))!.ParamName, + Is.EqualTo("kernel")); + Assert.That(Assert.Throws(() => kernelWithArguments.Execute2DAsync(extent, 1, 2, 3, 4, 5))!.ParamName, + Is.EqualTo("kernel")); + } + [Test] public static void UntypedLaunchRejectsIncorrectScalarAndArrayTypesBeforeCompilation() { diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index ff7dbd5..ebc6960 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -297,10 +297,12 @@ internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) /// Checks whether the compiled kernel method is currently cached on this GPU. /// The delegate identifying the kernel method. /// True if the method has a compiled cache entry. + /// is null. /// This GPU has been disposed. public bool IsCompiled(Delegate kernel) { ThrowIfDisposed(); + ArgumentNullException.ThrowIfNull(kernel); return compiler.IsCompiled(kernel); } /// Removes compiled kernel entries from this GPU's cache. diff --git a/Kernelium/TypedKernelExtensions.cs b/Kernelium/TypedKernelExtensions.cs index c1581b4..fa6e6d2 100644 --- a/Kernelium/TypedKernelExtensions.cs +++ b/Kernelium/TypedKernelExtensions.cs @@ -8,32 +8,44 @@ public static class TypedKernelExtensions /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// The typed kernel to launch. /// The positive logical dimensions. Guard both global indices against this extent. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent) => + Index2D extent) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// The typed kernel to launch. /// The positive logical dimensions. Guard both global indices against this extent. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent) => - kernel.Execute2DAsync(extent.X, extent.Y, extent); + Index2D extent) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent); + } /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. /// The typed kernel to launch. /// The positive logical dimensions. Guard both global indices against this extent. /// Argument for kernel parameter 2. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent, KernelArgument argument1) => + Index2D extent, KernelArgument argument1) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent, argument1); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -41,11 +53,15 @@ public static void Execute2D(this TypedKernel kernel, /// The positive logical dimensions. Guard both global indices against this extent. /// Argument for kernel parameter 2. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent, KernelArgument argument1) => - kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1); + Index2D extent, KernelArgument argument1) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1); + } /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -54,11 +70,15 @@ public static Task Execute2DAsync(this TypedKernel kernel, /// The positive logical dimensions. Guard both global indices against this extent. /// Argument for kernel parameter 2. /// Argument for kernel parameter 3. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2) => + Index2D extent, KernelArgument argument1, KernelArgument argument2) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -68,11 +88,15 @@ public static void Execute2D(this TypedKernel kernel, /// Argument for kernel parameter 2. /// Argument for kernel parameter 3. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2) => - kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2); + Index2D extent, KernelArgument argument1, KernelArgument argument2) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2); + } /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -83,11 +107,15 @@ public static Task Execute2DAsync(this TypedKernel kern /// Argument for kernel parameter 2. /// Argument for kernel parameter 3. /// Argument for kernel parameter 4. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -99,11 +127,15 @@ public static void Execute2D(this TypedKernel k /// Argument for kernel parameter 3. /// Argument for kernel parameter 4. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) => - kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3); + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3); + } /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -116,11 +148,15 @@ public static Task Execute2DAsync(this TypedKernelArgument for kernel parameter 3. /// Argument for kernel parameter 4. /// Argument for kernel parameter 5. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -134,11 +170,15 @@ public static void Execute2D(this TypedKernelArgument for kernel parameter 4. /// Argument for kernel parameter 5. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) => - kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4); + } /// Runs a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -153,11 +193,15 @@ public static Task Execute2DAsync(this TypedKernelArgument for kernel parameter 4. /// Argument for kernel parameter 5. /// Argument for kernel parameter 6. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static void Execute2D(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) + { + ArgumentNullException.ThrowIfNull(kernel); kernel.Execute2D(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); + } /// Submits a 2D launch and passes the logical extent as the first kernel argument. /// Type of kernel parameter 2. @@ -173,9 +217,13 @@ public static void Execute2D(this TypedKernelArgument for kernel parameter 5. /// Argument for kernel parameter 6. /// A task that completes after execution and any requested host copy-back. + /// is null. /// A logical dimension is nonpositive or exceeds supported launch limits. /// The owning GPU has been disposed. public static Task Execute2DAsync(this TypedKernel kernel, - Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) => - kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); + Index2D extent, KernelArgument argument1, KernelArgument argument2, KernelArgument argument3, KernelArgument argument4, KernelArgument argument5) + { + ArgumentNullException.ThrowIfNull(kernel); + return kernel.Execute2DAsync(extent.X, extent.Y, extent, argument1, argument2, argument3, argument4, argument5); + } } From 9d238565706d4013eab1b773fe3ce042d447c1c6 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 19:53:00 +0100 Subject: [PATCH 10/11] Remove preview compatibility APIs for 1.0 --- Kernelium.Test/AsyncKernelExecution.cs | 4 +- Kernelium.Test/KernelExecution.cs | 5 +- Kernelium.Test/TypedKernelTests.cs | 6 +- Kernelium/DataTypes/GPUConfiguration.cs | 8 -- Kernelium/Enums/HardwareType.cs | 20 ----- Kernelium/GPU.cs | 106 ------------------------ README.md | 12 +-- llms.txt | 3 +- 8 files changed, 11 insertions(+), 153 deletions(-) delete mode 100644 Kernelium/Enums/HardwareType.cs diff --git a/Kernelium.Test/AsyncKernelExecution.cs b/Kernelium.Test/AsyncKernelExecution.cs index b61b4c9..e1ad1ee 100644 --- a/Kernelium.Test/AsyncKernelExecution.cs +++ b/Kernelium.Test/AsyncKernelExecution.cs @@ -13,7 +13,7 @@ public static async Task OneDimensionalAndExplicitLaunchesCopyBackBeforeCompleti { using var gpu = CreateCpu(); var copy = gpu.CreateKernel(CopyAndClear); - var increment = gpu.CreateKernel(TestHelper.Increment, precompile: false); + var increment = gpu.CreateKernel(TestHelper.Increment, CompilationStrategy.Lazy); int[] source = [2, 3, 4]; int[] output = new int[source.Length]; int[] readWrite = [5, 6, 7]; @@ -106,7 +106,7 @@ public static async Task BufferAliasesAndDefaultStreamTransfersUseSubmissionOrde public static async Task ConcurrentHostSubmissionsCompleteOnOneCpuAccelerator() { using var gpu = CreateCpu(); - var increment = gpu.CreateKernel(TestHelper.Increment, precompile: false); + var increment = gpu.CreateKernel(TestHelper.Increment, CompilationStrategy.Lazy); int[] shared = new int[13]; var independent = Enumerable.Range(0, 16).Select(value => new[] { value }).ToArray(); var submissions = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index 5206670..60235eb 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -1,6 +1,7 @@ using ILGPU; using ILGPU.Runtime; using ILGPU.Runtime.Cuda; +using Kernelium.Enums; namespace Kernelium.Test { @@ -158,7 +159,7 @@ public static void CpuRejectsLaunchesWithTooManyPaddedThreads() public static void Execute2DRejectsNonPositiveDimensions(int width, int height, string parameter) { using var gpu = new GPU(new() { ComputeBackend = Enums.ComputeBackend.Cpu }); - var kernel = gpu.CreateKernel(DoublePixel, precompile: false); + var kernel = gpu.CreateKernel(DoublePixel, CompilationStrategy.Lazy); var error = Assert.Throws(() => kernel.Execute2D(width, height)); @@ -509,7 +510,7 @@ public static void ExecuteWithoutPrecompilation() var kernel = gpu.CreateKernel( TestHelper.Fill, - precompile: false); + CompilationStrategy.Lazy); int[] data = new int[32]; diff --git a/Kernelium.Test/TypedKernelTests.cs b/Kernelium.Test/TypedKernelTests.cs index 78832c7..b5bfabc 100644 --- a/Kernelium.Test/TypedKernelTests.cs +++ b/Kernelium.Test/TypedKernelTests.cs @@ -74,7 +74,7 @@ public static void DisposedGpuRejectsCompilationAndCacheAccess() public static async Task TypedLaunchesAcceptScalarsAndArrayAdapters() { using var gpu = new GPU(new() { ComputeBackend = ComputeBackend.Cpu }); - var kernel = gpu.CreateTypedKernel, ArrayView>(Add, precompile: false); + var kernel = gpu.CreateTypedKernel, ArrayView>(Add, CompilationStrategy.Lazy); int[] input = [1, 2, 3]; int[] result = new int[input.Length]; @@ -113,7 +113,7 @@ public static void InvalidTypedArgumentFaultsTheTaskAndReportsTheError() ComputeBackend = ComputeBackend.Cpu, ExecutionDiagnostics = info => report = info }); - var kernel = gpu.CreateTypedKernel(UnusedReference, precompile: false); + var kernel = gpu.CreateTypedKernel(UnusedReference, CompilationStrategy.Lazy); Task execution = kernel.ExecuteAsync(1, default); var error = Assert.ThrowsAsync(() => execution); @@ -135,7 +135,7 @@ public static async Task DiagnosticsReportLaunchesAndPreserveFailuresWhenTheCall throw new InvalidOperationException("Observer failure."); } }); - var kernel = gpu.CreateKernel(Add, precompile: false); + var kernel = gpu.CreateKernel(Add, CompilationStrategy.Lazy); int[] input = [1, 2, 3]; int[] result = new int[input.Length]; diff --git a/Kernelium/DataTypes/GPUConfiguration.cs b/Kernelium/DataTypes/GPUConfiguration.cs index 0f777a6..e3f70a2 100644 --- a/Kernelium/DataTypes/GPUConfiguration.cs +++ b/Kernelium/DataTypes/GPUConfiguration.cs @@ -8,14 +8,6 @@ public class GPUConfiguration /// The backend to use. The default is automatic device selection. public ComputeBackend ComputeBackend { get; set; } = ComputeBackend.Auto; - /// Compatibility alias for . - [Obsolete("Use ComputeBackend instead.")] - public HardwareType HardwareType - { - get => (HardwareType)ComputeBackend; - set => ComputeBackend = (ComputeBackend)value; - } - /// Index within the explicitly selected backend. Auto selects its own device. public int DeviceIndex { get; set; } diff --git a/Kernelium/Enums/HardwareType.cs b/Kernelium/Enums/HardwareType.cs deleted file mode 100644 index 6b2cd25..0000000 --- a/Kernelium/Enums/HardwareType.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Kernelium.Enums -{ - /// Compatibility names for . - [Obsolete("Use ComputeBackend instead.")] - public enum HardwareType - { - /// Use an OpenCL device and its compatible runtime. - OpenCL, - /// Use an NVIDIA device and its CUDA driver. - Cuda, - /// Use the ILGPU CPU accelerator. - Cpu, - /// Let ILGPU select the preferred available device. - Auto - } -} diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index ebc6960..3587bcf 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -70,11 +70,6 @@ public GPU(GPUConfiguration? config = null) throw; } } - /// - [Obsolete("Use CreateKernel instead.")] - public Kernel GenerateKernel(Delegate kernel, bool precompile = true) => - CreateKernel(kernel, precompile); - /// Creates a reusable kernel whose arguments are checked at launch. /// A static method or a noncapturing lambda supported by ILGPU. /// When to compile the kernel. The default is eager compilation. @@ -91,16 +86,6 @@ public Kernel CreateKernel(Delegate kernel, CompilationStrategy strategy = Compi return instance; } - /// Creates a reusable kernel whose arguments are checked at launch. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast, captures state, or returns a value. - /// This GPU has been disposed. - public Kernel CreateKernel(Delegate kernel, bool precompile) => - CreateKernel(kernel, precompile ? CompilationStrategy.Eager : CompilationStrategy.Lazy); - /// Creates a reusable kernel with typed arguments. /// A static method or a noncapturing lambda supported by ILGPU. /// When to compile the kernel. The default is eager compilation. @@ -112,16 +97,6 @@ public Kernel CreateKernel(Delegate kernel, bool precompile) => public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// A static method or a noncapturing lambda supported by ILGPU. @@ -134,17 +109,6 @@ public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -158,18 +122,6 @@ public TypedKernel CreateTypedKernel(Action kernel, bool precompile) public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// Type of kernel parameter 2. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -184,19 +136,6 @@ public TypedKernel CreateTypedKernel(Action kernel, bool public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// Type of kernel parameter 2. - /// Type of kernel parameter 3. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -212,20 +151,6 @@ public TypedKernel CreateTypedKernel(Action public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// Type of kernel parameter 2. - /// Type of kernel parameter 3. - /// Type of kernel parameter 4. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -242,21 +167,6 @@ public TypedKernel CreateTypedKernel(Action CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// Type of kernel parameter 2. - /// Type of kernel parameter 3. - /// Type of kernel parameter 4. - /// Type of kernel parameter 5. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - /// Creates a reusable kernel with typed arguments. /// Type of kernel parameter 1. /// Type of kernel parameter 2. @@ -274,22 +184,6 @@ public TypedKernel CreateTypedKernel(Act public TypedKernel CreateTypedKernel(Action kernel, CompilationStrategy strategy = CompilationStrategy.Eager) => new(CreateKernel(kernel, strategy)); - /// Creates a reusable kernel with typed arguments. - /// Type of kernel parameter 1. - /// Type of kernel parameter 2. - /// Type of kernel parameter 3. - /// Type of kernel parameter 4. - /// Type of kernel parameter 5. - /// Type of kernel parameter 6. - /// A static method or a noncapturing lambda supported by ILGPU. - /// True to compile during creation. False to compile on first launch. - /// A kernel associated with this GPU. - /// is null. - /// The delegate is multicast or captures state. - /// The owning GPU has been disposed. - public TypedKernel CreateTypedKernel(Action kernel, bool precompile) => - new(CreateKernel(kernel, precompile)); - internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) { return operations.UseAccelerator(() => compiler.GetOrCompile(kernel)); diff --git a/README.md b/README.md index 7b8b8d9..f1e4626 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,7 @@ To build against the checkout, add a project reference to `Kernelium/Kernelium.c 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. For 1.0.0, use -`gpu.CreateKernel(...)` and `ComputeBackend = ComputeBackend.Cpu` in place of -the preview names `GenerateKernel` and `HardwareType`. The preview names -remain available as obsolete aliases. - -If you used `GPU.ConvertParameters` in a preview, pass arguments directly to -`Execute` or `ExecuteAsync` for Kernelium-managed transfers. For direct ILGPU -launches, pass device views such as `GPUBuffer.View` to the ILGPU launcher. +directions, and reusable device buffers. Use `CreateTypedKernel` for compile-time argument checks, `GPUConfiguration.CudaPinnedStagingCacheBytes` to tune CUDA staging, and @@ -175,8 +168,7 @@ kernel.Compile(); ``` A manual launch throws if the cache has no compiled entry for the method. -Call `Compile()` again after clearing the cache. Existing -`precompile: false` calls are equivalent to `CompilationStrategy.Lazy`. +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 diff --git a/llms.txt b/llms.txt index c6fee76..f323da7 100644 --- a/llms.txt +++ b/llms.txt @@ -36,7 +36,7 @@ static void DoubleValues(ArrayView input, ArrayView output) - Set `ComputeBackend.Cuda` for a CUDA-capable NVIDIA device, `ComputeBackend.OpenCL` for a compatible OpenCL runtime, or `ComputeBackend.Auto` for ILGPU's preferred available device. `DeviceIndex` selects a device for an explicit backend. - An explicit backend requires the corresponding runtime and device. GPU construction throws if the backend or device is unavailable. -- `CreateKernel` compiles eagerly by default. Both kernel factories accept `CompilationStrategy`. `Eager` compiles at creation, `Lazy` compiles on the first launch, and `Manual` requires a compiled cache entry before launch. Use `Compile()` to populate that entry. `precompile: false` still selects lazy compilation. `Execute` returns after the kernel and any copy-back complete. +- `CreateKernel` compiles eagerly by default. Both kernel factories accept `CompilationStrategy`. `Eager` compiles at creation, `Lazy` compiles on the first launch, and `Manual` requires a compiled cache entry before launch. Use `Compile()` to populate that entry. `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. The work-item count, width, and height must be positive. 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. Kernels must be static methods or non-capturing lambdas that return `void`. Use ILGPU's supported subset of C# and write results through `ArrayView`. @@ -73,7 +73,6 @@ await Task.WhenAll( - Use `gpu.CreateTypedKernel(Method)` for zero to six kernel parameters. To infer the types, first assign the method group to a local variable. The typed launch checks count and types at compile time. Pass scalars and views directly. Use `KernelArgument.Input`, `Output`, or `ReadWrite` for host arrays and `KernelArgument.Buffer` for a device buffer. - Set `GPUConfiguration.ExecutionDiagnostics` to receive a `KernelExecutionInfo` report after each launch attempt, including invalid extents and arguments. Reports include the selected backend and device, resolved launch dimensions when available, requested host-array transfer bytes, host elapsed time, and any exception. Use `KernelName` for readable local function names. Callbacks may run concurrently. - Set `GPUConfiguration.BufferTransferDiagnostics` to observe explicit buffer uploads and downloads. Reports include direction, requested bytes, device, host elapsed time, and any exception. -- `CreateKernel` and `ComputeBackend` replace the obsolete preview names `GenerateKernel` and `HardwareType`. ## ILGPU interop From 1c40e23b3ac01b536733f2d310e918575c680b52 Mon Sep 17 00:00:00 2001 From: sepp4122 Date: Mon, 30 Nov 2026 20:11:19 +0100 Subject: [PATCH 11/11] Initialize OpenCL independently of CUDA --- Kernelium.Test/AsyncKernelExecution.cs | 2 +- Kernelium.Test/KernelExecution.cs | 2 +- Kernelium/GPU.cs | 6 +++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Kernelium.Test/AsyncKernelExecution.cs b/Kernelium.Test/AsyncKernelExecution.cs index e1ad1ee..8c37467 100644 --- a/Kernelium.Test/AsyncKernelExecution.cs +++ b/Kernelium.Test/AsyncKernelExecution.cs @@ -199,7 +199,7 @@ public static async Task GpuDisposalDrainsQueuedWork() [TestCase(ComputeBackend.OpenCL, AcceleratorType.OpenCL)] public static async Task AsyncStreamsAndDefaultStreamInterop(ComputeBackend hardware, AcceleratorType accelerator) { - using var context = Context.CreateDefault(); + using var context = GPU.CreateContext(hardware); if (!context.Devices.Any(device => device.AcceleratorType == accelerator)) Assert.Ignore($"{accelerator} accelerator unavailable."); diff --git a/Kernelium.Test/KernelExecution.cs b/Kernelium.Test/KernelExecution.cs index 60235eb..76aed2a 100644 --- a/Kernelium.Test/KernelExecution.cs +++ b/Kernelium.Test/KernelExecution.cs @@ -49,7 +49,7 @@ public static void ExecuteParameterlessKernelOnGpu( Enums.ComputeBackend hardwareType, AcceleratorType acceleratorType) { - using var context = Context.CreateDefault(); + using var context = GPU.CreateContext(hardwareType); if (!context.Devices.Any(device => device.AcceleratorType == acceleratorType)) Assert.Ignore($"{acceleratorType} accelerator unavailable."); diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index 3587bcf..b102196 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -42,7 +42,7 @@ public GPU(GPUConfiguration? config = null) long stagingBudget = config.CudaPinnedStagingCacheBytes; ArgumentOutOfRangeException.ThrowIfNegative(stagingBudget, nameof(config.CudaPinnedStagingCacheBytes)); - context = Context.CreateDefault(); + context = CreateContext(config.ComputeBackend); try { accelerator = config.ComputeBackend switch @@ -70,6 +70,10 @@ public GPU(GPUConfiguration? config = null) throw; } } + internal static Context CreateContext(ComputeBackend backend) => backend == ComputeBackend.OpenCL + ? Context.Create(builder => builder.OpenCL()) + : Context.CreateDefault(); + /// Creates a reusable kernel whose arguments are checked at launch. /// A static method or a noncapturing lambda supported by ILGPU. /// When to compile the kernel. The default is eager compilation.