diff --git a/Kernelium.Test/AsyncKernelExecution.cs b/Kernelium.Test/AsyncKernelExecution.cs new file mode 100644 index 0000000..4c7041d --- /dev/null +++ b/Kernelium.Test/AsyncKernelExecution.cs @@ -0,0 +1,372 @@ +using ILGPU; +using ILGPU.Runtime; +using Kernelium.Enums; +using Kernelium.Execution; + +namespace Kernelium.Test; + +[TestFixture] +public static class AsyncKernelExecution +{ + [Test] + public static async Task OneDimensionalAndExplicitLaunchesCopyBackBeforeCompletion() + { + using var gpu = CreateCpu(); + var copy = gpu.GenerateKernel(CopyAndClear); + var increment = gpu.GenerateKernel(TestHelper.Increment, precompile: false); + int[] source = [2, 3, 4]; + int[] output = new int[source.Length]; + int[] readWrite = [5, 6, 7]; + + await Task.WhenAll( + copy.ExecuteAsync(source.Length, ArrayArgument.Input(source), ArrayArgument.Output(output)), + increment.ExecuteAsync(new KernelConfig(readWrite.Length, 1), readWrite)); + + Assert.That(output, Is.EqualTo(source)); + Assert.That(source, Is.EqualTo(new[] { 2, 3, 4 })); + Assert.That(readWrite, Is.EqualTo(new[] { 6, 7, 8 })); + } + + [Test] + public static async Task TwoDimensionalLaunchCopiesEveryCoordinate() + { + using var gpu = CreateCpu(); + var kernel = gpu.GenerateKernel(WritePixel); + const int width = 19; + const int height = 17; + var output = new int[width * height]; + + await kernel.Execute2DAsync(width, height, width, height, ArrayArgument.Output(output)); + + Assert.That(output, Is.EqualTo(Enumerable.Range(1, output.Length))); + } + + [Test] + public static async Task DuplicateHostArgumentsUseSeparateDeviceAllocations() + { + using var gpu = CreateCpu(); + var kernel = gpu.GenerateKernel(ClearThenCopy); + int[] data = [3, 4]; + + await kernel.ExecuteAsync(data.Length, ArrayArgument.Input(data), data, ArrayArgument.Output(data)); + + Assert.That(data, Is.EqualTo(new[] { 3, 4 })); + } + + [Test] + public static async Task CapturesParameterEntriesAndOrdersHostWritesAcrossGpuInstances() + { + using var firstGpu = CreateCpu(); + using var secondGpu = CreateCpu(); + var square = firstGpu.GenerateKernel(TestHelper.Square); + var increment = secondGpu.GenerateKernel(TestHelper.Increment); + int[] data = [2, 3]; + int[] replacement = [8, 9]; + object[] parameters = [data]; + + Task first; + Task second; + using (Hold(data)) + { + first = square.ExecuteAsync(data.Length, parameters); + parameters[0] = replacement; + second = increment.ExecuteAsync(data.Length, data); + Assert.That(first.IsCompleted, Is.False); + Assert.That(second.IsCompleted, Is.False); + } + + await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(data, Is.EqualTo(new[] { 5, 10 })); + Assert.That(replacement, Is.EqualTo(new[] { 8, 9 })); + } + + [Test] + public static async Task BufferAliasesAndDefaultStreamTransfersUseSubmissionOrder() + { + 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 first = increment.ExecuteAsync(4, buffer); + var second = nested.ExecuteAsync(2, new NestedView(buffer.View.SubView(1, 2))); + square.Execute(4, buffer.View); + Assert.That(buffer.Download(), Is.EqualTo(new[] { 4, 16, 25, 25 })); + + buffer.Upload(new[] { 7, 8, 9, 10 }); + var third = increment.ExecuteAsync(4, buffer.View.SubView(0, 4)); + int[] destination = new int[4]; + buffer.Download(destination); + await Task.WhenAll(first, second, third); + Assert.That(destination, Is.EqualTo(new[] { 8, 9, 10, 11 })); + } + + [Test] + public static async Task ConcurrentHostSubmissionsCompleteOnOneCpuAccelerator() + { + using var gpu = CreateCpu(); + var increment = gpu.GenerateKernel(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); + var calls = independent.Select(async array => + { + await submissions.Task; + await Task.WhenAll(increment.ExecuteAsync(shared.Length, shared), increment.ExecuteAsync(1, array)); + }).ToArray(); + + submissions.SetResult(); + await Task.WhenAll(calls).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(shared, Is.All.EqualTo(independent.Length)); + Assert.That(independent.Select(array => array[0]), Is.EqualTo(Enumerable.Range(1, independent.Length))); + } + + [Test] + public static async Task AsyncFailureFaultsItsTaskAndLaterConflictCanProceed() + { + using var gpu = CreateCpu(); + var increment = gpu.GenerateKernel(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); + Task valid = increment.ExecuteAsync(1, data); + + Assert.ThrowsAsync(async () => await invalid); + Assert.ThrowsAsync(async () => await increment.ExecuteAsync(0, data)); + Assert.ThrowsAsync(async () => await increment.ExecuteAsync(1, null!)); + await valid; + Assert.That(data[0], Is.EqualTo(5)); + } + + [Test] + public static async Task BufferDisposalWaitsForAcceptedViewUses() + { + using var gpu = CreateCpu(); + using var buffer = gpu.Upload(new[] { 11 }); + var copy = gpu.GenerateKernel(TestHelper.Copy); + var alias = buffer.View.SubView(0, 1); + var allocation = OperationScheduler.For(buffer.Allocation); + int[] output = new int[1]; + Task pending; + Task dispose; + using (Hold(output)) + { + pending = copy.ExecuteAsync(1, alias, ArrayArgument.Output(output)); + dispose = Task.Run(buffer.Dispose); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!OperationScheduler.IsClosed(allocation)) + { + timeout.Token.ThrowIfCancellationRequested(); + await Task.Yield(); + } + Assert.That(dispose.IsCompleted, Is.False); + Assert.ThrowsAsync(async () => await copy.ExecuteAsync(1, alias, output)); + } + + await Task.WhenAll(pending, dispose).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(output[0], Is.EqualTo(11)); + } + + [Test] + public static async Task GpuDisposalDrainsQueuedWork() + { + using var gpu = CreateCpu(); + using var buffer = gpu.Upload(new[] { 13 }); + var copy = gpu.GenerateKernel(TestHelper.Copy); + int[] output = new int[1]; + Task pending; + Task dispose; + using (Hold(output)) + { + pending = copy.ExecuteAsync(1, buffer, ArrayArgument.Output(output)); + dispose = Task.Run(gpu.Dispose); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (CanGetView(buffer)) + { + timeout.Token.ThrowIfCancellationRequested(); + await Task.Yield(); + } + Assert.That(dispose.IsCompleted, Is.False); + Assert.ThrowsAsync(async () => await copy.ExecuteAsync(1, buffer, output)); + } + + await Task.WhenAll(pending, dispose).WaitAsync(TimeSpan.FromSeconds(10)); + 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) + { + 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 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); + int[] first = [5, 6]; + int[] second = [7, 8]; + + raw(new KernelConfig(2, 1), buffer.View); + square.Execute(2, buffer); + await Task.WhenAll(increment.ExecuteAsync(2, buffer), + increment.ExecuteAsync(2, first), increment.ExecuteAsync(2, second)); + raw(new KernelConfig(2, 1), buffer.View); + Assert.That(buffer.Download(), Is.EqualTo(new[] { 18, 27 })); + Assert.That(first, Is.EqualTo(new[] { 6, 7 })); + Assert.That(second, Is.EqualTo(new[] { 8, 9 })); + } + + [Test] + public static void CudaBufferTransfersReuseStagingAcrossSizesAndTypes() + { + 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 }); + using var small = gpu.Allocate(3); + using var large = gpu.Allocate(4); + + small.Upload([1, 2, 3]); + Assert.That(small.Download(), Is.EqualTo(new byte[] { 1, 2, 3 })); + large.Upload([10, 20, 30, 40]); + Assert.That(large.Download(), Is.EqualTo(new long[] { 10, 20, 30, 40 })); + small.Upload([5, 6, 7]); + Assert.That(small.Download(), Is.EqualTo(new byte[] { 5, 6, 7 })); + Assert.That(large.Download(), Is.EqualTo(new long[] { 10, 20, 30, 40 })); + } + + [Test] + public static async Task CudaHostArrayLaunchesPreserveAliasedArgumentsAcrossRepeatedSubmissions() + { + 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); + for (int length = 17; length >= 1; length -= 8) + { + int[] expected = Enumerable.Range(1, length).ToArray(); + int[] sync = (int[])expected.Clone(); + int[] first = (int[])expected.Clone(); + int[] second = expected.Select(value => -value).ToArray(); + + copy.Execute(length, ArrayArgument.Input(sync), sync, ArrayArgument.Output(sync)); + await Task.WhenAll( + copy.ExecuteAsync(length, ArrayArgument.Input(first), first, ArrayArgument.Output(first)), + copy.ExecuteAsync(length, ArrayArgument.Input(second), second, ArrayArgument.Output(second))); + + Assert.That(sync, Is.EqualTo(expected)); + Assert.That(first, Is.EqualTo(expected)); + Assert.That(second, Is.EqualTo(expected.Select(value => -value))); + } + } + + [Test] + public static void CudaStagingCacheEnforcesBudgetAndReusesExistingRegions() + { + 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 pool = new CudaStagingPool(gpu.Accelerator, byteBudget: 64); + var first = pool.TryRent(0, 32); + var second = pool.TryRent(1, 16); + + Assert.That(first, Is.Not.Null); + Assert.That(second, Is.Not.Null); + Assert.That(pool.TryRent(2, 32), Is.Null); + Assert.That(pool.TryRent(0, 64), Is.Null); + Assert.That(pool.TryRent(0, 16), Is.SameAs(first)); + Assert.That(pool.TryRent(1, 32)!.Capacity, Is.EqualTo(32)); + Assert.That(pool.TryRent(2, 1), Is.Null); + } + + [Test] + public static async Task LaunchesAcceptCovariantParamsArraysWithoutReplacingCallerEntries() + { + using var gpu = CreateCpu(); + using var buffer = gpu.Upload(new[] { 4 }); + var increment = gpu.GenerateKernel(TestHelper.Increment); + var bufferParameters = new[] { buffer }; + int[] data = [7]; + int[][] hostParameters = [data]; + + await increment.ExecuteAsync(1, bufferParameters); + increment.Execute(1, hostParameters); + + Assert.That(bufferParameters[0], Is.SameAs(buffer)); + Assert.That(hostParameters[0], Is.SameAs(data)); + Assert.That(buffer.Download(), Is.EqualTo(new[] { 5 })); + Assert.That(data, Is.EqualTo(new[] { 8 })); + } + + private static GPU CreateCpu() => new(new() { HardwareType = HardwareType.Cpu }); + + private static OperationScheduler.Reservation Hold(int[] data) + { + var claims = new OperationScheduler.Claims(); + claims.Add(OperationScheduler.For(data), write: true); + return OperationScheduler.Reserve(claims); + } + + private static bool CanGetView(Memory.GPUBuffer buffer) + { + try + { + _ = buffer.View; + return true; + } + catch (ObjectDisposedException) + { + return false; + } + } + + private static void CopyAndClear(ArrayView input, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + { + output[index] = input[index]; + input[index] = 0; + } + } + + private static void ClearThenCopy(ArrayView input, ArrayView other, ArrayView output) + { + int index = Grid.GlobalIndex.X; + if (index < output.Length) + { + other[index] = 0; + output[index] = input[index]; + } + } + + private static void WritePixel(int width, int height, ArrayView output) + { + int x = Grid.GlobalIndex.X; + int y = Grid.GlobalIndex.Y; + if (x < width && y < height) + output[y * width + x] = y * width + x + 1; + } + + private static void IncrementNested(NestedView data) + { + int index = Grid.GlobalIndex.X; + if (index < data.View.Length) + data.View[index]++; + } + + public readonly struct NestedView(ArrayView view) + { + public readonly ArrayView View = view; + } +} diff --git a/Kernelium.Test/DeviceOperationsTests.cs b/Kernelium.Test/DeviceOperationsTests.cs new file mode 100644 index 0000000..0a545fb --- /dev/null +++ b/Kernelium.Test/DeviceOperationsTests.cs @@ -0,0 +1,39 @@ +using Kernelium.Execution; + +namespace Kernelium.Test; + +[TestFixture] +internal static class DeviceOperationsTests +{ + [TestCase(true)] + [TestCase(false)] + public static void FailedFinalDrainPreservesRetainedWork(bool hasRetainedWork) + { + bool released = false; + bool quarantined = false; + var failure = new InvalidOperationException("Final drain failed."); + + var error = Assert.Throws(() => DeviceOperations.DrainThenRelease( + drain: () => throw failure, + release: () => released = true, + quarantine: () => quarantined = true, + hasRetainedWork)); + + Assert.That(error, Is.SameAs(failure)); + Assert.That(released, Is.EqualTo(!hasRetainedWork)); + Assert.That(quarantined, Is.EqualTo(hasRetainedWork)); + } + + [Test] + public static void SuccessfulFinalDrainReleasesRetainedWork() + { + var calls = new List(); + DeviceOperations.DrainThenRelease( + drain: () => calls.Add("drain"), + release: () => calls.Add("release"), + quarantine: () => Assert.Fail("Completed work does not need quarantine."), + hasRetainedWork: true); + + Assert.That(calls, Is.EqualTo(new[] { "drain", "release" })); + } +} diff --git a/Kernelium.Test/GPUBufferTests.cs b/Kernelium.Test/GPUBufferTests.cs index caddd43..2e1c6b2 100644 --- a/Kernelium.Test/GPUBufferTests.cs +++ b/Kernelium.Test/GPUBufferTests.cs @@ -126,6 +126,8 @@ public static void KernelRejectsDisposedBufferAndPreviouslyObtainedView() var kernel = gpu.GenerateKernel(TestHelper.Increment); buffer.Dispose(); + Assert.That(((IArrayView)buffer.NativeView).Buffer, Is.SameAs(((IArrayView)view).Buffer)); + Assert.Throws(() => kernel.Execute(new KernelConfig(1, 1), buffer)); Assert.Throws(() => diff --git a/Kernelium.Test/OperationSchedulerTests.cs b/Kernelium.Test/OperationSchedulerTests.cs new file mode 100644 index 0000000..4d254b3 --- /dev/null +++ b/Kernelium.Test/OperationSchedulerTests.cs @@ -0,0 +1,149 @@ +using Kernelium.Execution; +using static Kernelium.Execution.OperationScheduler; + +namespace Kernelium.Test; + +[TestFixture] +internal static class OperationSchedulerTests +{ + [Test] + public static async Task IndependentOperationsAndReadersPassAWaitingWriterOnOtherResources() + { + var shared = new Resource(); + var unrelated = new Resource(); + using var firstReader = Claim((shared, false)); + using var secondReader = Claim((shared, false)); + using var writer = Claim((shared, true)); + using var laterReader = Claim((shared, false)); + using var independent = Claim((unrelated, true)); + + Assert.That(firstReader.Predecessors.IsCompletedSuccessfully, Is.True); + Assert.That(secondReader.Predecessors.IsCompletedSuccessfully, Is.True); + Assert.That(independent.Predecessors.IsCompletedSuccessfully, Is.True); + Assert.That(writer.Predecessors.IsCompleted, Is.False); + Assert.That(laterReader.Predecessors.IsCompleted, Is.False); + + // Hold the second reader after releasing the first. + firstReader.Dispose(); + Assert.That(writer.Predecessors.IsCompleted, Is.False); + secondReader.Dispose(); + await writer.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(laterReader.Predecessors.IsCompleted, Is.False); + writer.Dispose(); + await laterReader.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + } + + [Test] + public static async Task MultiResourceClaimsReserveTogetherAndMergeDuplicateAccess() + { + var a = new Resource(); + var b = new Resource(); + using var first = Claim((a, true)); + using var second = Claim((b, true)); + using var combined = Claim((a, false), (b, true), (a, true)); + using var later = Claim((a, false), (b, false)); + + first.Dispose(); + Assert.That(combined.Predecessors.IsCompleted, Is.False); + Assert.That(later.Predecessors.IsCompleted, Is.False); + second.Dispose(); + await combined.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(later.Predecessors.IsCompleted, Is.False); + combined.Dispose(); + await later.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + } + + [Test] + public static async Task FailedWorkReleasesItsReservationWithoutFaultingSuccessors() + { + var resource = new Resource(); + var fail = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var failed = FailAfterGate(); + using var successor = Claim((resource, true)); + Assert.That(successor.Predecessors.IsCompleted, Is.False); + + fail.SetResult(); + Assert.ThrowsAsync(async () => await failed); + await successor.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + + async Task FailAfterGate() + { + using var operation = Claim((resource, true)); + await fail.Task; + throw new InvalidOperationException(); + } + } + + [Test] + public static async Task CloseRejectsNewWorkAndDrainsQueuedUsesBeforeReleasing() + { + var resource = new Resource(); + var independent = new Resource(); + using var active = Claim((resource, true)); + using var queued = Claim((resource, true)); + var released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var dispose = Task.Run(() => Close(resource, () => released.SetResult())); + + await WaitUntilClosed(resource); + Assert.Throws(() => Claim((independent, true), (resource, true))); + using var unrelated = Claim((independent, true)); + Assert.That(unrelated.Predecessors.IsCompletedSuccessfully, Is.True); + var concurrentDispose = Task.Run(() => Close(resource, () => Assert.Fail("Released twice."))); + Assert.That(released.Task.IsCompleted, Is.False); + + active.Dispose(); + await queued.Predecessors.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(released.Task.IsCompleted, Is.False); + queued.Dispose(); + await Task.WhenAll(dispose, concurrentDispose).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.That(released.Task.IsCompletedSuccessfully, Is.True); + } + + [Test] + public static async Task BufferCloseKeepsOwnerAliveUntilNativeReleaseCompletes() + { + var owner = new Resource(); + var buffer = new Resource(); + using var use = Claim((owner, false), (buffer, true)); + var bufferReleased = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var bufferDispose = Task.Run(() => Close(buffer, () => bufferReleased.SetResult(), owner)); + await WaitUntilClosed(buffer); + var ownerDispose = Task.Run(() => Close(owner, () => + Assert.That(bufferReleased.Task.IsCompletedSuccessfully, Is.True))); + await WaitUntilClosed(owner); + + use.Dispose(); + await Task.WhenAll(bufferDispose, ownerDispose).WaitAsync(TimeSpan.FromSeconds(10)); + } + + [Test] + public static void ReservingClaimsPreventsFurtherMutationOrReuse() + { + var resource = new Resource(); + var claims = new Claims(); + claims.Add(resource, write: true); + + using var reservation = Reserve(claims); + + Assert.Throws(() => claims.Add(new Resource(), write: false)); + Assert.Throws(() => Reserve(claims)); + } + + private static Reservation Claim(params (Resource Resource, bool Write)[] access) + { + var claims = new Claims(); + foreach (var (resource, write) in access) + claims.Add(resource, write); + return Reserve(claims); + } + + private static async Task WaitUntilClosed(Resource resource) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + while (!IsClosed(resource)) + { + timeout.Token.ThrowIfCancellationRequested(); + await Task.Yield(); + } + } +} diff --git a/Kernelium.Test/StreamWorkTests.cs b/Kernelium.Test/StreamWorkTests.cs new file mode 100644 index 0000000..60da070 --- /dev/null +++ b/Kernelium.Test/StreamWorkTests.cs @@ -0,0 +1,85 @@ +using System.Collections.Concurrent; +using ILGPU.Runtime; +using Kernelium.Enums; +using Kernelium.Execution; + +namespace Kernelium.Test; + +[TestFixture] +internal static class StreamWorkTests +{ + [Test] + public static void FailedStreamDrainRetainsResourcesAndPreventsReuse() + { + using var gpu = new GPU(new() { HardwareType = HardwareType.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]); + work.Own(temporary); + + Assert.Throws(() => work.Run(() => { })); + + Assert.That(work.Retired, Is.True); + Assert.That(temporary.Disposed, Is.False); + Assert.That(retained, Does.Contain(temporary)); + 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] + public static void ReportsOperationFailureAlongsideDrainFailure() + { + using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + using var stream = new FailingStream(gpu.Accelerator); + var work = new StreamWork(stream, new ConcurrentBag(), []); + var operationError = new ArgumentException("Launch failed."); + + var error = Assert.Throws(() => work.Run(() => throw operationError)); + + Assert.That(error!.InnerExceptions[0], Is.SameAs(operationError)); + Assert.That(error.InnerExceptions[1].Message, Is.EqualTo("Stream completion is unknown.")); + Assert.That(work.Retired, Is.True); + } + + [Test] + public static void ReportsOperationFailureAlongsideCleanupFailure() + { + using var gpu = new GPU(new() { HardwareType = HardwareType.Cpu }); + var work = new StreamWork(gpu.Accelerator.DefaultStream, new ConcurrentBag(), []); + var operationError = new ArgumentException("Launch failed."); + var cleanupError = new InvalidOperationException("Cleanup failed."); + work.Own(new FailingResource(cleanupError)); + + var error = Assert.Throws(() => work.Run(() => throw operationError)); + + Assert.That(error!.Flatten().InnerExceptions, Is.EqualTo(new Exception[] { operationError, cleanupError })); + Assert.That(work.Retired, Is.False); + } + + private sealed class FailingResource(Exception error) : IDisposable + { + public void Dispose() => throw error; + } + + private sealed class TrackingResource : IDisposable + { + internal bool Disposed { get; private set; } + + public void Dispose() => Disposed = true; + } + + private sealed class FailingStream(Accelerator accelerator) : AcceleratorStream(accelerator) + { + public override void Synchronize() => throw new InvalidOperationException("Stream completion is unknown."); + + protected override ProfilingMarker AddProfilingMarkerInternal() => throw new NotSupportedException(); + + protected override void DisposeAcceleratorObject(bool disposing) { } + } +} diff --git a/Kernelium/Execution/CudaReadback.cs b/Kernelium/Execution/CudaReadback.cs new file mode 100644 index 0000000..d08f843 --- /dev/null +++ b/Kernelium/Execution/CudaReadback.cs @@ -0,0 +1,32 @@ +using System.Runtime.InteropServices; +using ILGPU; +using ILGPU.Runtime; +using ILGPU.Runtime.Cuda; + +namespace Kernelium.Execution; + +internal static partial class CudaReadback +{ + internal static bool IsSupported => OperatingSystem.IsWindows() || OperatingSystem.IsLinux(); + + internal static unsafe void Copy(ArrayView view, T[] destination) where T : unmanaged + { + // The synchronous driver call completes the copy before returning, so + // the CLR only needs to pin the destination for the duration of the call. + fixed (T* host = destination) + { + IntPtr device = view.LoadEffectiveAddressAsPtr(); + var bytes = new UIntPtr((ulong)CudaStaging.ByteCount(destination.Length)); + var result = OperatingSystem.IsWindows() + ? CopyWindows((IntPtr)host, device, bytes) + : CopyLinux((IntPtr)host, device, bytes); + CudaException.ThrowIfFailed(result); + } + } + + [LibraryImport("nvcuda.dll", EntryPoint = "cuMemcpyDtoH_v2")] + private static partial CudaError CopyWindows(IntPtr destination, IntPtr source, UIntPtr bytes); + + [LibraryImport("libcuda.so.1", EntryPoint = "cuMemcpyDtoH_v2")] + private static partial CudaError CopyLinux(IntPtr destination, IntPtr source, UIntPtr bytes); +} diff --git a/Kernelium/Execution/CudaStaging.cs b/Kernelium/Execution/CudaStaging.cs new file mode 100644 index 0000000..dc43510 --- /dev/null +++ b/Kernelium/Execution/CudaStaging.cs @@ -0,0 +1,74 @@ +using System.Runtime.CompilerServices; +using ILGPU; +using ILGPU.Runtime; +using ILGPU.Runtime.Cuda; + +namespace Kernelium.Execution; + +// A dedicated CUDA host allocation avoids registering overlapping pages +// when small managed staging arrays are allocated by concurrent launches. +internal sealed class CudaStaging : AcceleratorObject +{ + private readonly IntPtr pointer; + internal long Capacity { get; } + + internal CudaStaging(Accelerator accelerator, long capacity) : base(accelerator) + { + Capacity = capacity; + CudaException.ThrowIfFailed(CudaAPI.CurrentAPI.AllocateHostMemory(out pointer, new IntPtr(capacity))); + } + + internal static long ByteCount(int length) where T : unmanaged => (long)length * Unsafe.SizeOf(); + + internal unsafe Span AsSpan(int length) where T : unmanaged => new(pointer.ToPointer(), length); + + internal void Copy(AcceleratorStream stream, ArrayView view, int length, bool upload) where T : unmanaged + { + var bytes = new IntPtr(ByteCount(length)); + IntPtr device = view.LoadEffectiveAddressAsPtr(); + CudaException.ThrowIfFailed(upload + ? CudaAPI.CurrentAPI.MemcpyAsync(device, pointer, bytes, stream) + : CudaAPI.CurrentAPI.MemcpyAsync(pointer, device, bytes, stream)); + } + + protected override void DisposeAcceleratorObject(bool disposing) + { + if (pointer == IntPtr.Zero) + return; + + var result = CudaAPI.CurrentAPI.FreeHostMemory(pointer); + if (disposing) + CudaException.ThrowIfFailed(result); + } +} + +// 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) +{ + private readonly List regions = new(); + private long cachedBytes; + + internal CudaStaging? TryRent(int index, long bytes) + { + if (index == regions.Count) + regions.Add(null); + + var previous = regions[index]; + if (previous is not null && previous.Capacity >= bytes) + return previous; + + long previousBytes = previous?.Capacity ?? 0; + if (bytes > byteBudget - (cachedBytes - previousBytes)) + return null; + + regions[index] = null; + cachedBytes -= previousBytes; + previous?.Dispose(); + + var staging = new CudaStaging(accelerator, bytes); + regions[index] = staging; + cachedBytes += bytes; + return staging; + } +} diff --git a/Kernelium/Execution/DeviceOperations.cs b/Kernelium/Execution/DeviceOperations.cs new file mode 100644 index 0000000..d8cb507 --- /dev/null +++ b/Kernelium/Execution/DeviceOperations.cs @@ -0,0 +1,201 @@ +using System.Collections.Concurrent; +using ILGPU.Runtime; + +namespace Kernelium.Execution; + +internal sealed class DeviceOperations +{ + // A driver may still hold native pointers after a failed drain. Keep the + // accelerator and its retained resources rooted until process exit. + private static readonly ConcurrentBag undrainedDevices = new(); + + private sealed class Slot + { + internal AcceleratorStream? Stream; + internal CudaStagingPool? Staging; + } + + private readonly Accelerator accelerator; + private readonly bool isCpu; + 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(); + + internal OperationScheduler.Resource Lifetime { get; } = new(); + + internal DeviceOperations(Accelerator accelerator) + { + this.accelerator = accelerator; + isCpu = accelerator.AcceleratorType == AcceleratorType.CPU; + int count = isCpu ? 1 : 2; + available = new(count, count); + for (int i = 0; i < count; i++) + slots.Enqueue(new Slot()); + } + + internal OperationScheduler.Claims GetClaims(bool useDefaultStream) + { + var claims = new OperationScheduler.Claims(); + claims.Add(Lifetime, write: false); + if (useDefaultStream) + claims.Add(defaultStream, write: true); + return claims; + } + + internal T Run(OperationScheduler.Claims claims, MemoryBuffer[] allocations, + Func action) + { + using var reservation = OperationScheduler.Reserve(claims); + reservation.Predecessors.GetAwaiter().GetResult(); + if (isCpu) + available.Wait(); + try + { + reservation.CheckResources(); + using var binding = accelerator.BindScoped(); + return RunOnStream(defaultSlot, accelerator.DefaultStream, allocations, action, + () => defaultStream.UnsafeToUse = true); + } + finally + { + if (isCpu) + available.Release(); + } + } + + internal async Task RunAsync(OperationScheduler.Claims claims, MemoryBuffer[] allocations, Action action) + { + using var reservation = OperationScheduler.Reserve(claims); + await reservation.Predecessors.ConfigureAwait(false); + await available.WaitAsync().ConfigureAwait(false); + + if (!slots.TryDequeue(out var slot)) + { + available.Release(); + throw new InvalidOperationException("No execution slot was available after acquiring a permit."); + } + + try + { + await Task.Run(() => + { + reservation.CheckResources(); + using var binding = accelerator.BindScoped(); + var stream = isCpu ? accelerator.DefaultStream : slot.Stream ??= accelerator.CreateStream(); + RunOnStream(slot, stream, allocations, work => + { + action(work); + return true; + }, () => + { + if (isCpu) + defaultStream.UnsafeToUse = true; + else + slot.Stream = null; + }); + }).ConfigureAwait(false); + } + finally + { + slots.Enqueue(slot); + available.Release(); + } + } + + private T RunOnStream(Slot slot, AcceleratorStream stream, MemoryBuffer[] allocations, + Func action, Action retire) + { + if (accelerator.AcceleratorType == AcceleratorType.Cuda) + slot.Staging ??= new CudaStagingPool(accelerator); + var work = new StreamWork(stream, retained, allocations, slot.Staging); + try + { + T result = default!; + work.Run(() => result = action(work)); + return result; + } + finally + { + if (work.Retired) + { + retained.Add(stream); + if (slot.Staging is { } staging) + { + retained.Add(staging); + slot.Staging = null; + } + retire(); + } + } + } + + internal T UseAccelerator(Func action) + { + using var reservation = OperationScheduler.Reserve(GetClaims(useDefaultStream: false)); + return action(); + } + + internal void Dispose(Action tearDown) + { + OperationScheduler.Close(Lifetime, () => + { + bool hasRetainedWork = !retained.IsEmpty; + try + { + DrainThenRelease( + drain: () => + { + if (!accelerator.IsDisposed) + accelerator.Synchronize(); + else if (hasRetainedWork) + throw new InvalidOperationException("The accelerator was disposed before retained work could be drained."); + }, + release: () => + { + // ILGPU disposes its child streams and buffers with the accelerator. + tearDown(); + defaultSlot.Staging = null; + retained.Clear(); + slots.Clear(); + }, + quarantine: () => undrainedDevices.Add(this), + hasRetainedWork); + } + finally + { + available.Dispose(); + } + }); + } + + internal static void DrainThenRelease(Action drain, Action release, Action quarantine, bool hasRetainedWork) + { + try + { + drain(); + } + catch (Exception drainError) + { + if (hasRetainedWork) + { + quarantine(); + throw; + } + + try + { + release(); + } + catch (Exception releaseError) + { + throw new AggregateException("The accelerator drain and teardown both failed.", drainError, releaseError); + } + + throw; + } + + release(); + } +} diff --git a/Kernelium/Execution/KernelExecutor.cs b/Kernelium/Execution/KernelExecutor.cs index a9b5868..ef5a741 100644 --- a/Kernelium/Execution/KernelExecutor.cs +++ b/Kernelium/Execution/KernelExecutor.cs @@ -10,147 +10,76 @@ internal sealed class KernelExecutor private readonly Accelerator accelerator; private readonly KernelCompiler compiler; private readonly ParameterMarshaller marshaller; + private readonly DeviceOperations operations; + + internal LaunchSizing Sizing { get; } + public KernelExecutor( Accelerator accelerator, KernelCompiler compiler, - ParameterMarshaller marshaller) + ParameterMarshaller marshaller, + DeviceOperations operations) { this.accelerator = accelerator; this.compiler = compiler; this.marshaller = marshaller; + this.operations = operations; + Sizing = new LaunchSizing(accelerator); } - public void Execute(Delegate kernel, KernelConfig config, params object[] parameters) + internal void Execute(Delegate kernel, Func getConfig, object[] parameters) { - ValidateArguments(kernel, parameters); - Launch(compiler.GetOrCompile(kernel), config, parameters); + var (captured, claims, allocations) = Capture(kernel, parameters, useDefaultStream: true); + operations.Run(claims, allocations, work => + { + Launch(kernel, getConfig, captured, work); + return true; + }); } - public void Execute( - Delegate kernel, - int workItems, - params object[] parameters) + internal async Task ExecuteAsync(Delegate kernel, Func getConfig, object[] parameters) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems); - ValidateArguments(kernel, parameters); - - var compiled = compiler.GetOrCompile(kernel); - int threads = accelerator.EstimateGroupSize(compiled); - int blocks = DivideRoundUp(workItems, threads); - Launch(compiled, new KernelConfig(blocks, threads), parameters); + var (captured, claims, allocations) = Capture(kernel, parameters, useDefaultStream: false); + await operations.RunAsync(claims, allocations, work => Launch(kernel, getConfig, captured, work)) + .ConfigureAwait(false); } - public void Execute2D( - Delegate kernel, - int width, - int height, - params object[] parameters) + + private (object[] Parameters, OperationScheduler.Claims Claims, MemoryBuffer[] Allocations) Capture( + Delegate kernel, object[] parameters, bool useDefaultStream) { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); ValidateArguments(kernel, parameters); - - const int tileSize = 16; - var compiled = compiler.GetOrCompile(kernel); - int maxGroupSize = accelerator.MaxNumThreadsPerGroup; - if (compiled.Specialization.MaxNumThreadsPerGroup is int kernelLimit) - maxGroupSize = Math.Min(maxGroupSize, kernelLimit); - int preferredGroupSize = Math.Min(accelerator.EstimateGroupSize(compiled), maxGroupSize); - // On OpenCL this query returns a per-kernel limit. - if (accelerator.AcceleratorType == AcceleratorType.OpenCL) - maxGroupSize = preferredGroupSize; - - var maxGroup = accelerator.MaxGroupSize; - var maxGrid = accelerator.MaxGridSize; - - int minimumColumns = DivideRoundUp(width, maxGrid.X); - int minimumRows = DivideRoundUp(height, maxGrid.Y); - if (minimumColumns > Math.Min(maxGroup.X, maxGroupSize)) - throw new ArgumentOutOfRangeException(nameof(width), width, "The workload exceeds the device grid limit."); - if (minimumRows > Math.Min(maxGroup.Y, maxGroupSize / minimumColumns)) - throw new ArgumentOutOfRangeException(nameof(height), height, "The workload exceeds the device grid limit."); - - int minimumGroupSize = minimumColumns * minimumRows; - int groupSize = minimumGroupSize > preferredGroupSize ? maxGroupSize : preferredGroupSize; - int preferredColumns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); - int preferredRows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); - int columns = Math.Clamp(preferredColumns, minimumColumns, groupSize / minimumRows); - int rows = Math.Clamp(preferredRows, minimumRows, groupSize / columns); - - var group = new Index2D(columns, rows); - var grid = new Index2D( - GetBlockCount(width, columns, maxGrid.X, nameof(width)), - GetBlockCount(height, rows, maxGrid.Y, nameof(height)) - ); - Launch(compiled, new KernelConfig(grid, group), 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)); } - private void Launch( - ILGPU.Runtime.Kernel compiled, - KernelConfig config, - object[] parameters) + private void Launch(Delegate kernel, Func getConfig, + object[] parameters, StreamWork work) { - ValidateCpuLaunchSize(config); - List buffers = new(); - List copyBack = new(); - try + var compiled = compiler.GetOrCompile(kernel); + var config = getConfig(compiled); + Sizing.ValidateCpuLaunchSize(config); + marshaller.MarshalForLaunch(work, parameters); + // CUDA's parameterless wrapper has one unused argument. + if (parameters.Length == 0 && accelerator.AcceleratorType == AcceleratorType.Cuda && + compiled.NumParameters == 1) + parameters = new object[] { 0 }; + + work.KeepAlive(compiled); + if (accelerator.AcceleratorType == AcceleratorType.OpenCL) { - object[] gpuParameters = - marshaller.ConvertParameters( - buffers, - copyBack, - parameters - ); - // CUDA's parameterless wrapper has one unused argument. - if (gpuParameters.Length == 0 && accelerator.AcceleratorType == AcceleratorType.Cuda && - compiled.NumParameters == 1) - gpuParameters = new object[] { 0 }; - - compiled.Launch(accelerator.DefaultStream, config, gpuParameters); - accelerator.Synchronize(); - foreach (var copy in copyBack) - copy(); + // OpenCL keeps mutable argument bindings on the compiled kernel itself. + lock (compiled) + compiled.Launch(work.Stream, config, parameters); } - finally + else { - try - { - accelerator.Synchronize(); - } - finally - { - foreach (var buffer in buffers) - buffer.Dispose(); - } + compiled.Launch(work.Stream, config, parameters); } } - private 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) - throw new ArgumentOutOfRangeException(parameterName, length, - "The workload exceeds the device grid limit with the selected group size."); - - return groups; - } - - private static int DivideRoundUp(int length, int divisor) => - (int)((length + (long)divisor - 1) / divisor); - - private void ValidateCpuLaunchSize(KernelConfig config) - { - if (accelerator.AcceleratorType != AcceleratorType.CPU || !config.IsValid) - return; - - long width = (long)config.GridDim.X * config.GroupDim.X; - long height = (long)config.GridDim.Y * config.GroupDim.Y; - long depth = (long)config.GridDim.Z * config.GroupDim.Z; - - // ILGPU's CPU launcher flattens the padded extent into a 32-bit index. - if (width > int.MaxValue / height || width * height > int.MaxValue / depth) - throw new ArgumentOutOfRangeException(nameof(config), - "A CPU launch cannot exceed Int32.MaxValue threads after rounding to whole groups."); - } - private static void ValidateArguments(Delegate kernel, object[] parameters) { ArgumentNullException.ThrowIfNull(parameters); diff --git a/Kernelium/Execution/LaunchSizing.cs b/Kernelium/Execution/LaunchSizing.cs new file mode 100644 index 0000000..ee239b1 --- /dev/null +++ b/Kernelium/Execution/LaunchSizing.cs @@ -0,0 +1,92 @@ +using ILGPU; +using ILGPU.Runtime; +using System.Runtime.CompilerServices; +using CompiledKernel = ILGPU.Runtime.Kernel; + +namespace Kernelium.Execution; + +internal sealed class LaunchSizing +{ + private readonly Accelerator accelerator; + private readonly ConditionalWeakTable groupSizes = new(); + private readonly ConditionalWeakTable.CreateValueCallback estimateGroupSize; + + private sealed record PreferredGroupSize(int Threads); + + internal LaunchSizing(Accelerator accelerator) + { + this.accelerator = accelerator; + estimateGroupSize = compiled => new PreferredGroupSize(accelerator.EstimateGroupSize(compiled)); + } + + internal KernelConfig For1D(CompiledKernel compiled, int workItems) + { + int threads = groupSizes.GetValue(compiled, estimateGroupSize).Threads; + int blocks = DivideRoundUp(workItems, threads); + return new KernelConfig(blocks, threads); + } + + internal KernelConfig For2D(CompiledKernel compiled, int width, int height) + { + const int tileSize = 16; + int maxGroupSize = accelerator.MaxNumThreadsPerGroup; + if (compiled.Specialization.MaxNumThreadsPerGroup is int kernelLimit) + maxGroupSize = Math.Min(maxGroupSize, kernelLimit); + int preferredGroupSize = Math.Min(groupSizes.GetValue(compiled, estimateGroupSize).Threads, maxGroupSize); + // On OpenCL this query returns a per-kernel limit. + if (accelerator.AcceleratorType == AcceleratorType.OpenCL) + maxGroupSize = preferredGroupSize; + + var maxGroup = accelerator.MaxGroupSize; + var maxGrid = accelerator.MaxGridSize; + + int minimumColumns = DivideRoundUp(width, maxGrid.X); + int minimumRows = DivideRoundUp(height, maxGrid.Y); + if (minimumColumns > Math.Min(maxGroup.X, maxGroupSize)) + throw new ArgumentOutOfRangeException(nameof(width), width, "The workload exceeds the device grid limit."); + if (minimumRows > Math.Min(maxGroup.Y, maxGroupSize / minimumColumns)) + throw new ArgumentOutOfRangeException(nameof(height), height, "The workload exceeds the device grid limit."); + + int minimumGroupSize = minimumColumns * minimumRows; + int groupSize = minimumGroupSize > preferredGroupSize ? maxGroupSize : preferredGroupSize; + int preferredColumns = Math.Min(width, Math.Min(tileSize, maxGroup.X)); + int preferredRows = Math.Min(height, Math.Min(tileSize, maxGroup.Y)); + int columns = Math.Clamp(preferredColumns, minimumColumns, groupSize / minimumRows); + int rows = Math.Clamp(preferredRows, minimumRows, groupSize / columns); + + var group = new Index2D(columns, rows); + var grid = new Index2D( + GetBlockCount(width, columns, maxGrid.X, nameof(width)), + GetBlockCount(height, rows, maxGrid.Y, nameof(height)) + ); + return new KernelConfig(grid, group); + } + + private 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) + throw new ArgumentOutOfRangeException(parameterName, length, + "The workload exceeds the device grid limit with the selected group size."); + + return groups; + } + + private static int DivideRoundUp(int length, int divisor) => + (int)((length + (long)divisor - 1) / divisor); + + internal void ValidateCpuLaunchSize(KernelConfig config) + { + if (accelerator.AcceleratorType != AcceleratorType.CPU || !config.IsValid) + return; + + long width = (long)config.GridDim.X * config.GroupDim.X; + long height = (long)config.GridDim.Y * config.GroupDim.Y; + long depth = (long)config.GridDim.Z * config.GroupDim.Z; + + // ILGPU's CPU launcher flattens the padded extent into a 32-bit index. + if (width > int.MaxValue / height || width * height > int.MaxValue / depth) + throw new ArgumentOutOfRangeException(nameof(config), + "A CPU launch cannot exceed Int32.MaxValue threads after rounding to whole groups."); + } +} diff --git a/Kernelium/Execution/OperationScheduler.cs b/Kernelium/Execution/OperationScheduler.cs new file mode 100644 index 0000000..d08dd78 --- /dev/null +++ b/Kernelium/Execution/OperationScheduler.cs @@ -0,0 +1,163 @@ +using System.Runtime.CompilerServices; + +namespace Kernelium.Execution; + +internal static class OperationScheduler +{ + private static readonly object admission = new(); + private static readonly ConditionalWeakTable resources = new(); + + internal sealed class Resource + { + internal Task? Writer; + internal readonly HashSet Readers = new(); + internal TaskCompletionSource? CloseCompletion; + internal volatile bool UnsafeToUse; + + internal void ThrowIfUnsafe() + { + if (UnsafeToUse) + throw new InvalidOperationException("A previous operation could not establish stream completion."); + } + } + + internal static Resource For(object key) => resources.GetValue(key, static _ => new()); + + internal sealed class Claims + { + private Dictionary? access = new(); + + internal void Add(Resource resource, bool write) + { + var pending = GetPendingAccess(); + pending[resource] = write || pending.GetValueOrDefault(resource); + } + + internal Dictionary TakeAccess() + { + var pending = GetPendingAccess(); + access = null; + return pending; + } + + private Dictionary GetPendingAccess() => + access ?? throw new InvalidOperationException("Resource claims have already been reserved."); + } + + internal sealed class Reservation( + Dictionary access, + Task predecessors, + TaskCompletionSource completion) : IDisposable + { + internal Task Predecessors => predecessors; + + internal void CheckResources() + { + foreach (var resource in access.Keys) + resource.ThrowIfUnsafe(); + } + + public void Dispose() + { + lock (admission) + { + if (completion.Task.IsCompleted) + return; + + foreach (var (resource, write) in access) + { + if (!write) + resource.Readers.Remove(completion.Task); + else if (resource.Writer == completion.Task) + resource.Writer = null; + } + completion.SetResult(); + } + } + } + + internal static Reservation Reserve(Claims claims) + { + lock (admission) + { + var access = claims.TakeAccess(); + foreach (var resource in access.Keys) + ObjectDisposedException.ThrowIf(resource.CloseCompletion is not null, resource); + + return ReserveLocked(access); + } + } + + private static Reservation ReserveLocked(Dictionary access) + { + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + HashSet? predecessors = null; + foreach (var (resource, write) in access) + { + if (resource.Writer is { } writer) + (predecessors ??= new()).Add(writer); + if (write) + { + if (resource.Readers.Count > 0) + { + (predecessors ??= new()).UnionWith(resource.Readers); + resource.Readers.Clear(); + } + resource.Writer = completion.Task; + } + else + { + resource.Readers.Add(completion.Task); + } + } + var ready = predecessors is null ? Task.CompletedTask : Task.WhenAll(predecessors); + return new Reservation(access, ready, completion); + } + + internal static bool IsClosed(Resource resource) + { + lock (admission) + return resource.CloseCompletion is not null; + } + + internal static void Close(Resource resource, Action release, Resource? owner = null) + { + Task wait; + TaskCompletionSource? closeCompletion = null; + Reservation? ownerUse = null; + Action? releaseAfterWait = null; + lock (admission) + { + if (resource.CloseCompletion is { } existing) + { + wait = existing.Task; + } + else + { + closeCompletion = resource.CloseCompletion = new(TaskCreationOptions.RunContinuationsAsynchronously); + releaseAfterWait = release; + wait = Task.WhenAll(resource.Readers.Append(resource.Writer ?? Task.CompletedTask)); + if (owner?.CloseCompletion is { } ownerClosed) + { + wait = Task.WhenAll(wait, ownerClosed.Task); + releaseAfterWait = null; + } + else if (owner is not null) + { + ownerUse = ReserveLocked(new() { [owner] = false }); + } + } + } + + try + { + wait.GetAwaiter().GetResult(); + releaseAfterWait?.Invoke(); + } + finally + { + ownerUse?.Dispose(); + closeCompletion?.SetResult(); + } + } +} diff --git a/Kernelium/Execution/StreamWork.cs b/Kernelium/Execution/StreamWork.cs new file mode 100644 index 0000000..617070d --- /dev/null +++ b/Kernelium/Execution/StreamWork.cs @@ -0,0 +1,222 @@ +using System.Collections.Concurrent; +using System.Runtime.ExceptionServices; +using ILGPU; +using ILGPU.Runtime; +using Kernelium.Memory; + +namespace Kernelium.Execution; + +internal sealed class StreamWork( + AcceleratorStream stream, + ConcurrentBag retained, + MemoryBuffer[] allocations, + CudaStagingPool? cudaStaging = null) : IArrayTransfers +{ + private readonly List temporary = new(); + private readonly List held = new(); + private IDisposable? ownedUntilSuccess; + private int stagingCount; + private readonly List downloads = new(); + private readonly List copyBack = new(); + + internal AcceleratorStream Stream => stream; + internal bool Retired { get; private set; } + internal void Own(IDisposable resource) => temporary.Add(resource); + + internal void KeepAlive(object resource) => held.Add(resource); + + internal void OwnUntilSuccess(IDisposable resource) => ownedUntilSuccess = resource; + + internal void Upload(ArrayView view, T[] data) where T : unmanaged + { + if (data.Length == 0) + return; + + if (stream.Accelerator.AcceleratorType == AcceleratorType.CPU) + { + view.CopyFromCPU(stream, data); + } + else if (stream.Accelerator.AcceleratorType == AcceleratorType.Cuda) + { + var staging = GetCudaStaging(data.Length); + UploadCuda(staging, view, data); + } + else + { + var staging = GC.AllocateUninitializedArray(data.Length, pinned: true); + KeepAlive(staging); + data.CopyTo(staging, 0); + view.CopyFromCPUUnsafeAsync(stream, ref staging[0], data.Length); + } + } + + void IArrayTransfers.TransferArray(MemoryBuffer1D buffer, T[] data, bool copyIn, bool copyOut) + { + Own(buffer); + ArrayView view = buffer.View; + if (data.Length == 0) + return; + + if (stream.Accelerator.AcceleratorType == AcceleratorType.Cuda) + { + var staging = GetCudaStaging(data.Length); + if (copyIn) + UploadCuda(staging, view, data); + if (copyOut) + downloads.Add(() => DownloadCuda(staging, view, data)); + return; + } + + if (copyIn) + Upload(view, data); + if (copyOut) + downloads.Add(() => Download(view, data)); + } + + internal void Download(ArrayView view, T[] data) where T : unmanaged + { + if (data.Length == 0) + return; + + if (stream.Accelerator.AcceleratorType == AcceleratorType.CPU) + { + copyBack.Add(() => view.CopyToCPU(stream, data)); + } + else if (stream.Accelerator.AcceleratorType == AcceleratorType.Cuda) + { + if (CudaReadback.IsSupported) + { + // Explicit downloads run on the default stream. Drain it before + // the blocking copy so it sees earlier work on that stream. + copyBack.Add(() => CudaReadback.Copy(view, data)); + } + else + { + var staging = GetCudaStaging(data.Length); + DownloadCuda(staging, view, data); + } + } + else + { + var staging = GC.AllocateUninitializedArray(data.Length, pinned: true); + KeepAlive(staging); + view.CopyToCPUUnsafeAsync(stream, ref staging[0], data.Length); + copyBack.Add(() => staging.CopyTo(data, 0)); + } + } + + internal void Run(Action action) + { + Exception? operationError = null; + try + { + action(); + foreach (var download in downloads) + download(); + } + catch (Exception error) + { + operationError = error; + } + + try + { + stream.Synchronize(); + } + catch (Exception drainError) + { + RetainUndrainedResources(); + if (operationError is not null) + throw new AggregateException("The operation and stream drain both failed.", operationError, drainError); + throw; + } + + if (operationError is null) + { + try + { + foreach (var copy in copyBack) + copy(); + } + catch (Exception error) + { + operationError = error; + } + } + + try + { + Cleanup(completed: operationError is null); + } + catch (Exception cleanupError) when (operationError is not null) + { + throw new AggregateException("The operation and temporary resource cleanup both failed.", + operationError, cleanupError); + } + + if (operationError is not null) + ExceptionDispatchInfo.Throw(operationError); + } + + private void RetainUndrainedResources() + { + Retired = true; + foreach (var allocation in allocations) + { + OperationScheduler.For(allocation).UnsafeToUse = true; + retained.Add(allocation); + } + if (ownedUntilSuccess is not null) + retained.Add(ownedUntilSuccess); + foreach (var resource in temporary) + retained.Add(resource); + foreach (var resource in held) + retained.Add(resource); + } + + private void Cleanup(bool completed) + { + List? errors = null; + for (int i = temporary.Count - 1; i >= 0; i--) + Release(temporary[i]); + if (ownedUntilSuccess is not null && (!completed || errors is not null)) + Release(ownedUntilSuccess); + if (errors is not null) + throw new AggregateException("Temporary device resource cleanup failed.", errors); + + void Release(IDisposable resource) + { + try + { + resource.Dispose(); + } + catch (Exception error) + { + (errors ??= new()).Add(error); + } + } + } + + private void UploadCuda(CudaStaging staging, ArrayView view, T[] data) where T : unmanaged + { + data.AsSpan().CopyTo(staging.AsSpan(data.Length)); + staging.Copy(stream, view, data.Length, upload: true); + } + + private void DownloadCuda(CudaStaging staging, ArrayView view, T[] data) where T : unmanaged + { + staging.Copy(stream, view, data.Length, upload: false); + copyBack.Add(() => staging.AsSpan(data.Length).CopyTo(data)); + } + + private CudaStaging GetCudaStaging(int length) where T : unmanaged + { + long bytes = CudaStaging.ByteCount(length); + if (cudaStaging?.TryRent(stagingCount++, bytes) is { } cached) + return cached; + + var staging = new CudaStaging(stream.Accelerator, bytes); + Own(staging); + return staging; + } +} diff --git a/Kernelium/GPU.cs b/Kernelium/GPU.cs index 058874b..2592d1a 100644 --- a/Kernelium/GPU.cs +++ b/Kernelium/GPU.cs @@ -18,6 +18,7 @@ public class GPU : IDisposable private readonly KernelCompiler compiler; private readonly KernelExecutor executor; private readonly ParameterMarshaller marshaller; + private readonly DeviceOperations operations; /// Information and capabilities for the selected device. public Device Device => accelerator.Device; @@ -40,12 +41,14 @@ public GPU(GPUConfiguration? config = null) HardwareType.Auto => context.GetPreferredDevice(false).CreateAccelerator(context), _ => throw new NotSupportedException() }; + operations = new DeviceOperations(accelerator); compiler = new KernelCompiler(accelerator); marshaller = new ParameterMarshaller(accelerator); executor = new KernelExecutor( accelerator, compiler, - marshaller + marshaller, + operations ); } catch @@ -63,7 +66,7 @@ public Kernel GenerateKernel(Delegate kernel, bool precompile = true) } internal ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel) { - return compiler.GetOrCompile(kernel); + return operations.UseAccelerator(() => compiler.GetOrCompile(kernel)); } public bool IsCompiled(Delegate kernel) { @@ -73,28 +76,40 @@ public void ClearKernelCache() { compiler.Clear(); } - internal void Execute( - Delegate kernel, - KernelConfig config, - params object[] parameters) + internal void Execute(Delegate kernel, KernelConfig config, object[] parameters) => + executor.Execute(kernel, _ => config, parameters); + + internal void Execute(Delegate kernel, int workItems, object[] parameters) { - executor.Execute(kernel, config, parameters); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(workItems); + executor.Execute(kernel, compiled => executor.Sizing.For1D(compiled, workItems), parameters); } - internal void Execute( - Delegate kernel, - int workItems, - params object[] parameters) + + internal void Execute2D(Delegate kernel, int width, int height, object[] parameters) { - executor.Execute(kernel, workItems, parameters); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + executor.Execute(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters); } - internal void Execute2D( - Delegate kernel, - int width, - int height, - params object[] parameters) + + internal Task ExecuteAsync(Delegate 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 async Task Execute2DAsync(Delegate kernel, int width, int height, object[] parameters) { - executor.Execute2D(kernel, width, height, parameters); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); + await executor.ExecuteAsync(kernel, compiled => executor.Sizing.For2D(compiled, width, height), parameters) + .ConfigureAwait(false); } + public object[] ConvertParameters( List buffers, List copyBack, @@ -107,55 +122,45 @@ public object[] ConvertParameters( ); } /// Allocates a device buffer initialized to zero. - public GPUBuffer Allocate(int length) where T : unmanaged - { - var buffer = new GPUBuffer(accelerator, length); - try - { - buffer.View.MemSetToZero(); - accelerator.DefaultStream.Synchronize(); - return buffer; - } - catch - { - buffer.Dispose(); - throw; - } - } + public GPUBuffer Allocate(int length) where T : unmanaged => + CreateBuffer(length, null); + public GPUBuffer Upload(T[] data) where T : unmanaged { ArgumentNullException.ThrowIfNull(data); - var buffer = new GPUBuffer(accelerator, data.Length); - try + return CreateBuffer(data.Length, data); + } + + private GPUBuffer CreateBuffer(int length, T[]? data) where T : unmanaged + { + var claims = operations.GetClaims(useDefaultStream: true); + if (data is not null) + claims.Add(OperationScheduler.For(data), write: false); + + return operations.Run(claims, [], work => { - buffer.Upload(data); + var buffer = new GPUBuffer(accelerator, operations, length); + // Ownership transfers to the caller only once stream work has completed. + work.OwnUntilSuccess(buffer.Allocation); + if (data is null) + buffer.NativeView.MemSetToZero(work.Stream); + else + work.Upload(buffer.NativeView, data); return buffer; - } - catch - { - buffer.Dispose(); - throw; - } + }); } - public void Dispose() + + public void Dispose() => operations.Dispose(() => { try { - if (!accelerator.IsDisposed) - accelerator.Synchronize(); + compiler.Clear(); } finally { - try - { - compiler.Clear(); - } - finally - { - DisposeAcceleratorAndContext(); - } + DisposeAcceleratorAndContext(); } - } + }); private void DisposeAcceleratorAndContext() { diff --git a/Kernelium/Kernel.cs b/Kernelium/Kernel.cs index 1ac9fa0..e06019b 100644 --- a/Kernelium/Kernel.cs +++ b/Kernelium/Kernel.cs @@ -22,5 +22,18 @@ public Kernel(GPU gpu, Delegate method) /// 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); + /// Submits a one-dimensional workload and completes after host copy-back. + public Task ExecuteAsync(int workItems, params object[] parameters) => + GPU.ExecuteAsync(Method, workItems, parameters); + + /// Submits a workload with explicit grid and group dimensions. + public Task ExecuteAsync(KernelConfig config, params object[] parameters) => + GPU.ExecuteAsync(Method, 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); + } } \ No newline at end of file diff --git a/Kernelium/Kernelium.csproj b/Kernelium/Kernelium.csproj index 5729eca..4534fcd 100644 --- a/Kernelium/Kernelium.csproj +++ b/Kernelium/Kernelium.csproj @@ -4,9 +4,10 @@ net10.0 enable enable + true true Kernelium - 0.2.0-preview.1 + 0.3.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 @@ -24,6 +25,7 @@ + diff --git a/Kernelium/Memory/GPUBuffer.cs b/Kernelium/Memory/GPUBuffer.cs index d63e35e..7bdf707 100644 --- a/Kernelium/Memory/GPUBuffer.cs +++ b/Kernelium/Memory/GPUBuffer.cs @@ -1,58 +1,93 @@ using ILGPU; using ILGPU.Runtime; +using Kernelium.Execution; namespace Kernelium.Memory { public sealed class GPUBuffer : IDisposable, IGPUBuffer where T : unmanaged { private readonly MemoryBuffer1D buffer; + private readonly DeviceOperations operations; + private readonly OperationScheduler.Resource lifetime; + + internal ArrayView NativeView { get; } + internal MemoryBuffer Allocation { get; } + public long Length => buffer.Length; + /// Gets a view that is valid for the lifetime of the buffer. public ArrayView View { get { ThrowIfDisposed(); - return buffer.View; + lifetime.ThrowIfUnsafe(); + return NativeView; } } - internal GPUBuffer(Accelerator accelerator, int length) + + internal GPUBuffer(Accelerator accelerator, DeviceOperations operations, int length) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(length); - ObjectDisposedException.ThrowIf(accelerator.IsDisposed, accelerator); + this.operations = operations; buffer = accelerator.Allocate1D(length); + // ILGPU clears buffer.View on disposal. Keep the allocation identity + // stable so admission rejects a view captured during a concurrent close. + NativeView = buffer.View; + Allocation = ((IArrayView)NativeView).Buffer; + lifetime = OperationScheduler.For(Allocation); } + IArrayView IGPUBuffer.GetView() => View; + public void Upload(T[] data) { ArgumentNullException.ThrowIfNull(data); - ThrowIfDisposed(); - if (data.LongLength != Length) - throw new ArgumentException("Array length mismatch.", nameof(data)); - buffer.CopyFromCPU(data); + Transfer(data, upload: true); } + public T[] Download() { ThrowIfDisposed(); - return buffer.GetAsArray1D(); + var result = new T[Length]; + Download(result); + return result; } + public void Download(T[] destination) { ArgumentNullException.ThrowIfNull(destination); - ThrowIfDisposed(); - if (destination.LongLength != Length) - throw new ArgumentException("Array length mismatch.", nameof(destination)); - - buffer.CopyToCPU(destination); + Transfer(destination, upload: false); } - private void ThrowIfDisposed() + + private void Transfer(T[] data, bool upload) { - ObjectDisposedException.ThrowIf(buffer.IsDisposed || buffer.Accelerator.IsDisposed, this); + var view = View; + if (data.LongLength != Length) + throw new ArgumentException("Array length mismatch.", upload ? nameof(data) : "destination"); + + var claims = operations.GetClaims(useDefaultStream: true); + claims.Add(lifetime, write: upload); + claims.Add(OperationScheduler.For(data), write: !upload); + operations.Run(claims, [Allocation], work => + { + if (upload) + work.Upload(view, data); + else + work.Download(view, data); + return true; + }); } - public void Dispose() + private void ThrowIfDisposed() => + ObjectDisposedException.ThrowIf( + OperationScheduler.IsClosed(lifetime) || OperationScheduler.IsClosed(operations.Lifetime) || + buffer.IsDisposed || buffer.Accelerator.IsDisposed, this); + + public void Dispose() => OperationScheduler.Close(lifetime, () => { - buffer.Dispose(); - } + if (!lifetime.UnsafeToUse) + buffer.Dispose(); + }, operations.Lifetime); } } diff --git a/Kernelium/Memory/IArrayTransfers.cs b/Kernelium/Memory/IArrayTransfers.cs new file mode 100644 index 0000000..a01fd61 --- /dev/null +++ b/Kernelium/Memory/IArrayTransfers.cs @@ -0,0 +1,11 @@ +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 5dbdf9a..dea9fae 100644 --- a/Kernelium/Memory/ParameterMarshaller.cs +++ b/Kernelium/Memory/ParameterMarshaller.cs @@ -1,5 +1,6 @@ using ILGPU; using ILGPU.Runtime; +using Kernelium.Execution; using System.Reflection; using System.Runtime.CompilerServices; @@ -27,7 +28,19 @@ public object[] ConvertParameters( List copyBack, params object[] parameters) { - object[] result = new object[parameters.Length]; + 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++) { @@ -40,7 +53,8 @@ public object[] ConvertParameters( var arrayArgument = parameter as ArrayArgument; if ((arrayArgument?.Data ?? parameter) is not Array array) { - ValidateViews(parameter, i); + if (validateViews) + VisitViews(parameter, i, null); result[i] = parameter; continue; } @@ -53,13 +67,11 @@ public object[] ConvertParameters( bool copyOut = arrayArgument is null || !arrayArgument.IsInput; result[i] = marshalArrayMethod .MakeGenericMethod(elementType) - .Invoke(this, new object[] { buffers, copyBack, array, copyIn, copyOut })!; + .Invoke(this, new object[] { transfers, array, copyIn, copyOut })!; } - - return result; } - private void ValidateViews(object value, int parameterIndex) + private void VisitViews(object value, int parameterIndex, Action? visit) { if (value is IArrayView view) { @@ -71,6 +83,10 @@ private void ValidateViews(object value, int parameterIndex) 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); return; } @@ -86,32 +102,56 @@ private void ValidateViews(object value, int parameterIndex) foreach (var field in fields) { if (field.GetValue(value) is { } fieldValue) - ValidateViews(fieldValue, parameterIndex); + VisitViews(fieldValue, parameterIndex, visit); } } + internal MemoryBuffer[] Capture(object[] parameters, OperationScheduler.Claims claims) + { + var allocations = new HashSet(ReferenceEqualityComparer.Instance); + for (int i = 0; i < parameters.Length; i++) + { + object parameter = parameters[i]; + ArgumentNullException.ThrowIfNull(parameter); + if (parameter is IGPUBuffer buffer) + parameter = parameters[i] = buffer.GetView(); + + if (parameter is ArrayArgument argument) + claims.Add(OperationScheduler.For(argument.Data), write: !argument.IsInput); + else if (parameter is Array array) + claims.Add(OperationScheduler.For(array), write: true); + else + VisitViews(parameter, i, allocation => allocations.Add(allocation)); + } + + foreach (var allocation in allocations) + claims.Add(OperationScheduler.For(allocation), write: true); + return allocations.ToArray(); + } + private static bool MayContainView(Type type) => typeof(IArrayView).IsAssignableFrom(type) || (type.IsValueType && !type.IsPrimitive && !type.IsEnum); private ArrayView MarshalArray( - List buffers, - List copyBack, - T[] data, - bool copyIn, - bool copyOut) where T : unmanaged + IArrayTransfers transfers, T[] data, bool copyIn, bool copyOut) where T : unmanaged { var buffer = accelerator.Allocate1D(data.Length); - - buffers.Add(buffer); - - if (copyIn) - buffer.CopyFromCPU(data); - - if (copyOut) - copyBack.Add(() => buffer.CopyToCPU(data)); - + 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)); + } + } } } diff --git a/README.md b/README.md index 64b378e..717e9d5 100644 --- a/README.md +++ b/README.md @@ -6,14 +6,18 @@ Kernelium wraps ILGPU with a small API for compiling and launching kernels from [NuGet package](https://www.nuget.org/packages/Kernelium) · [Source repository](https://github.com/Hinterdorfer-Raphael/Kernelium) -Kernelium is in preview and is MIT licensed. The package targets .NET 10. +Kernelium is MIT licensed and targets .NET 10. ## Install +This README documents Kernelium 0.3.0. Install the package from NuGet: + ```sh -dotnet add package Kernelium --version 0.2.0-preview.1 +dotnet add package Kernelium --version 0.3.0 ``` +To build against the checkout, add a project reference to `Kernelium/Kernelium.csproj`. + ## 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. @@ -61,14 +65,30 @@ Use `DeviceIndex` to select a device when requesting an explicit backend. | Use ILGPU directly | `gpu.Accelerator` | | Compile a static C# kernel | `gpu.GenerateKernel(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)` | | Retrieve results | `buffer.Download()` or `buffer.Download(destination)` | | Launch over a 2D extent | `kernel.Execute2D(width, height, ...)` | | Set launch dimensions | `kernel.Execute(new KernelConfig(blocks, threadsPerBlock), ...)` | -For coding agents generating an integration, the [NuGet readme](https://www.nuget.org/packages/Kernelium#readme) includes the complete quickstart. The package also ships `llms.txt`, a compact reference to the same APIs and resource rules. +The package ships `llms.txt`, a compact reference to the same APIs and resource rules. The quickstart for each published version is available on NuGet. [NuGet README](https://www.nuget.org/packages/Kernelium#readme) + +## Benchmarks + +The November 28 release run measured 72 cases on a Ryzen 7 5700G and RTX 4060 Ti. +At 4096², Kernelium CUDA completed Mandelbrot in 12.11 ms versus 333.79 ms +for native-threaded C#. For 4096² vector addition split into two batches, CUDA +async submission averaged 11.44 ms versus 14.43 ms for serial submission. +The CUDA timings include output downloads. The run covered CUDA and CPU. +[Full benchmark results](benchmarks/results/2026-11-28.md) -See the [benchmark results](benchmarks/results/2026-11-28.md) for measurements against native C# and raw ILGPU on a Ryzen 7 5700G and RTX 4060 Ti. +The workspace project at `examples/Kernelium.Benchmarks` compares two serial +launches, two async launches submitted together, and two async launches +submitted from dedicated host threads. Run `dotnet run -c Release -- --filter "*Batches"` +from that project directory for timings that include downloads. Use +`--gpu-only` for the CUDA and GPU-backed OpenCL suite and +`--cuda-async-throughput` to compare CUDA serial and async launches with data +kept on the device. ## API Documentation @@ -105,8 +125,10 @@ kernel.Execute(length, (ArrayView)buffer.View); This example expects a kernel with a single `ArrayView` parameter. `GPU` owns the accelerator. Keep the `GPU` instance alive while using it and dispose your ILGPU buffers and streams before disposing the `GPU`. -Kernelium launches on the accelerator's default stream. Synchronize any -work on a custom stream before a Kernelium launch that depends on it. +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. #### GenerateKernel @@ -144,7 +166,11 @@ gpu.ClearKernelCache(); #### Dispose -Releases the accelerator and its associated resources. +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. +If a driver failure prevents Kernelium from confirming that retained work has +completed, disposal throws and preserves the affected native resources until +process exit. ```csharp gpu.Dispose(); @@ -176,15 +202,11 @@ bool compiled = kernel.IsCompiled; ## Execute a Kernel -Pass host arrays directly for a one-off launch. +Pass host arrays directly for a one-off launch. This uses `add`, `left`, +`right`, and `result` from the quickstart. ```csharp -float[] a = [1f, 2f, 3f]; -float[] b = [10f, 20f, 30f]; -var result = new float[a.Length]; - -var add = gpu.GenerateKernel(VectorAdd); -add.Execute(result.Length, a, b, result); +add.Execute(result.Length, left, right, result); // result contains [11f, 22f, 33f]. ``` @@ -201,8 +223,8 @@ unnecessary copies. The kernel still declares ordinary ILGPU array views. ```csharp add.Execute(result.Length, - ArrayArgument.Input(a), - ArrayArgument.Input(b), + ArrayArgument.Input(left), + ArrayArgument.Input(right), ArrayArgument.Output(result)); ``` @@ -211,6 +233,37 @@ the host array and downloads the result after a successful launch. The output has unspecified initial contents, so the kernel should write every element before download. Pass the plain array when the kernel needs both transfers. +### Submit work asynchronously + +Use `ExecuteAsync(workItems, ...)`, `ExecuteAsync(config, ...)`, or +`Execute2DAsync(width, height, ...)`. Each task reports its operation's errors and +completes successfully after the kernel, host copy-back, and temporary resource cleanup. + +The vector-add kernel from the quickstart can use the same stable inputs in two +submissions with separate outputs. + +```csharp +float[] first = new float[left.Length]; +float[] second = new float[left.Length]; + +await Task.WhenAll( + add.ExecuteAsync(first.Length, ArrayArgument.Input(left), ArrayArgument.Input(right), ArrayArgument.Output(first)), + add.ExecuteAsync(second.Length, ArrayArgument.Input(right), ArrayArgument.Input(left), ArrayArgument.Output(second))); +``` + +Kernelium borrows the arrays through task completion. You may read and share input-only +arrays while work is pending, and their contents must stay stable. Leave output and +read/write arrays untouched until every pending use completes. A repeated array +argument still gets a separate temporary device allocation for each parameter. + +Kernelium orders conflicting operations by submission, including synchronous launches +and buffer transfers. Uses of the same host array conflict when either operation writes, +even across GPU instances. Buffer arguments, slices, and nested views conflict when +they share a device allocation. Multiple host threads can submit work on every backend. +CUDA and OpenCL have two async streams per GPU and can overlap independent workloads +when the device and driver support it. Overlap depends on the resources each +kernel uses. ILGPU runs one kernel at a time per CPU accelerator. + ### Launch a 2D workload Call `Execute2D(width, height, ...)` to let Kernelium choose a group shape @@ -230,8 +283,9 @@ static void DoublePixel(int width, int height, ArrayView input, ArrayView(result.Length); add.Execute(result.Length, deviceA, deviceB, deviceResult); @@ -266,9 +320,15 @@ float[] values = deviceResult.Download(); its contents or `buffer.Download(destination)` to copy into an existing array. Both arrays must match the buffer length. A launch with a `GPUBuffer` uses its existing device allocation and leaves the result there until you download it. +On CUDA, each stream reuses pinned host staging for host-array arguments and +buffer uploads. Read/write array arguments use the same staging for upload and +copy-back. 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 +blocking CUDA copy directly into the destination array. -Use a buffer or its `View` with the `GPU` instance that created it. Keep that instance -and its buffers alive through the launch, and dispose the buffers when finished. +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. ## Architecture @@ -299,7 +359,7 @@ Kernelium inherits the kernel restrictions of ILGPU. GPU kernels must be compati In particular: -- Kernels must return `void`. +- Kernels must be static methods or non-capturing lambdas that return `void`. - Results are written to GPU memory. - Managed objects and arbitrary .NET APIs cannot be used directly inside kernels. - Hardware capabilities may differ between backends. diff --git a/benchmarks/results/2026-11-28.md b/benchmarks/results/2026-11-28.md index 585ebfe..5d9cf90 100644 --- a/benchmarks/results/2026-11-28.md +++ b/benchmarks/results/2026-11-28.md @@ -1,23 +1,30 @@ -# Benchmark results — 2026-11-28 +# Kernelium 0.3.0 benchmark results (2026-11-28) -These BenchmarkDotNet measurements compare Kernelium with raw ILGPU and native C# for vector addition and Mandelbrot workloads at 256², 1024², and 4096². Timings are means from repeated benchmark iterations. The full generated report is included below. +The November 28 release run completed 72 BenchmarkDotNet cases for vector addition and Mandelbrot at 256², 1024², and 4096². It covers native C#, raw ILGPU CPU and CUDA, and Kernelium CPU and CUDA. The report has no OpenCL measurements. The CPU backend is a development and debugging fallback for machines without a GPU. -## Highlights +## CUDA results at 4096² -- **Mandelbrot on CUDA scales well:** at 4096², Kernelium took 12.15 ms, versus 366 ms for C# using native threads and 1,862 ms for single-threaded C# (about 30× and 153× faster, respectively). -- **Vector addition is transfer-sensitive:** at 4096², Kernelium CUDA took 12.27 ms, close to single-threaded C# at 12.93 ms and slower than native-threaded C# at 10.62 ms. -- **Kernelium CUDA is close to raw ILGPU:** at 4096², raw ILGPU took 11.26 ms for vector addition and 12.10 ms for Mandelbrot. -- **The ILGPU CPU accelerator is slow for these cases:** at 4096², Kernelium CPU took 6.10 s for vector addition and 7.82 s for Mandelbrot; raw ILGPU was in the same range. -- **OpenCL was not measured in this run.** +| Workload | C# single thread | C# native threads | Raw ILGPU CUDA | Kernelium CUDA | +| --- | ---: | ---: | ---: | ---: | +| Vector addition | 12.32 ms | 10.30 ms | 11.27 ms | 11.28 ms | +| Mandelbrot | 1,860.33 ms | 333.79 ms | 12.21 ms | 12.11 ms | -## Test environment and scope +## Comparison with 0.2.0 preview + +On the same RTX 4060 Ti, the synchronous 4096² vector addition mean fell from 12.27 ms to 11.28 ms (8.1%), while raw ILGPU stayed around 11.27 ms. The other five synchronous Kernelium CUDA means changed by at most 2.3%. Both runs timed output readback. The preview report contains synchronous measurements only, so the async comparison below uses the serial batches from this 0.3.0 run. [0.2.0 preview benchmark report](https://github.com/Hinterdorfer-Raphael/Kernelium/blob/v0.2.0-preview.1/benchmarks/results/2026-11-28.md) + +## CUDA batch submission -- Windows 11, .NET 10.0.15, BenchmarkDotNet 0.15.8 -- AMD Ryzen 7 5700G (8 physical / 16 logical cores) -- NVIDIA GeForce RTX 4060 Ti -- 36 benchmark cases covering two workloads, three square sizes, and the available C#, Kernelium CPU/CUDA, and raw ILGPU CPU/CUDA implementations +Each case splits the total workload into two launches and downloads both outputs. At 4096², async submission reduced the vector addition mean by about 21% versus serial submission. Mandelbrot had similar means across all three modes at that size. At 256², async submission reduced the Mandelbrot mean from 203.75 μs to 146.63 μs and increased the vector addition mean from 108.67 μs to 125.71 μs. + +| 4096² workload | Serial | Async | Async from dedicated host threads | +| --- | ---: | ---: | ---: | +| Vector addition | 14.43 ms | 11.44 ms | 14.48 ms | +| Mandelbrot | 12.28 ms | 12.27 ms | 12.35 ms | + +## Test environment and scope -These numbers describe this machine and these benchmark implementations. Device buffers and input uploads are prepared outside the timed region; each timed GPU operation includes kernel execution, synchronization, and output download. The measurements therefore include readback cost and are not pure device-kernel throughput. +The run used Windows 11, .NET 10.0.15, BenchmarkDotNet 0.15.8, an AMD Ryzen 7 5700G, and an NVIDIA GeForce RTX 4060 Ti. Device allocation and input uploads were outside the timed region. Timed CUDA operations include kernel execution, synchronization, and output download. BenchmarkDotNet flagged possible multimodal distributions in the threaded CUDA async batch measurements. ## Full BenchmarkDotNet report @@ -31,46 +38,82 @@ AMD Ryzen 7 5700G with Radeon Graphics 3.80GHz, 1 CPU, 16 logical and 8 physical ``` -| Method | Side | Workload | Mean | Error | StdDev | Ratio | RatioSD | Allocated | Alloc Ratio | -|-------------------- |----- |----------- |----------------:|--------------:|--------------:|-------:|--------:|----------:|------------:| -| **CSharpSingleThread** | **256** | **VectorAdd** | **43.93 μs** | **0.116 μs** | **0.108 μs** | **1.00** | **0.00** | **-** | **NA** | -| CSharpNativeThreads | 256 | VectorAdd | 184.24 μs | 2.285 μs | 2.025 μs | 4.19 | 0.05 | - | NA | -| KerneliumCpu | 256 | VectorAdd | 24,335.26 μs | 73.200 μs | 61.125 μs | 553.94 | 1.88 | 672 B | NA | -| KerneliumCuda | 256 | VectorAdd | 92.76 μs | 0.512 μs | 0.479 μs | 2.11 | 0.01 | 576 B | NA | -| RawIlgpuCpu | 256 | VectorAdd | 24,209.11 μs | 148.434 μs | 138.846 μs | 551.06 | 3.33 | 224 B | NA | -| RawIlgpuCuda | 256 | VectorAdd | 89.67 μs | 0.257 μs | 0.215 μs | 2.04 | 0.01 | 128 B | NA | -| | | | | | | | | | | -| **CSharpSingleThread** | **256** | **Mandelbrot** | **7,358.86 μs** | **3.628 μs** | **3.216 μs** | **1.00** | **0.00** | **-** | **NA** | -| CSharpNativeThreads | 256 | Mandelbrot | 1,730.83 μs | 8.817 μs | 7.816 μs | 0.24 | 0.00 | - | NA | -| KerneliumCpu | 256 | Mandelbrot | 30,781.64 μs | 46.016 μs | 43.044 μs | 4.18 | 0.01 | 536 B | NA | -| KerneliumCuda | 256 | Mandelbrot | 118.06 μs | 0.114 μs | 0.101 μs | 0.02 | 0.00 | 488 B | NA | -| RawIlgpuCpu | 256 | Mandelbrot | 30,923.93 μs | 219.908 μs | 205.702 μs | 4.20 | 0.03 | 689 B | NA | -| RawIlgpuCuda | 256 | Mandelbrot | 115.57 μs | 0.279 μs | 0.261 μs | 0.02 | 0.00 | 128 B | NA | -| | | | | | | | | | | -| **CSharpSingleThread** | **1024** | **VectorAdd** | **702.59 μs** | **2.515 μs** | **2.229 μs** | **1.00** | **0.00** | **-** | **NA** | -| CSharpNativeThreads | 1024 | VectorAdd | 310.25 μs | 2.524 μs | 2.361 μs | 0.44 | 0.00 | - | NA | -| KerneliumCpu | 1024 | VectorAdd | 379,326.23 μs | 5,686.950 μs | 5,319.577 μs | 539.90 | 7.52 | 672 B | NA | -| KerneliumCuda | 1024 | VectorAdd | 802.58 μs | 0.985 μs | 0.823 μs | 1.14 | 0.00 | 528 B | NA | -| RawIlgpuCpu | 1024 | VectorAdd | 397,255.80 μs | 4,130.953 μs | 3,864.096 μs | 565.42 | 5.60 | 224 B | NA | -| RawIlgpuCuda | 1024 | VectorAdd | 799.50 μs | 1.336 μs | 1.184 μs | 1.14 | 0.00 | 112 B | NA | -| | | | | | | | | | | -| **CSharpSingleThread** | **1024** | **Mandelbrot** | **118,544.58 μs** | **543.711 μs** | **508.587 μs** | **1.000** | **0.01** | **-** | **NA** | -| CSharpNativeThreads | 1024 | Mandelbrot | 22,701.90 μs | 221.850 μs | 207.519 μs | 0.192 | 0.00 | - | NA | -| KerneliumCpu | 1024 | Mandelbrot | 488,938.67 μs | 2,989.305 μs | 2,649.941 μs | 4.125 | 0.03 | 536 B | NA | -| KerneliumCuda | 1024 | Mandelbrot | 920.86 μs | 0.556 μs | 0.464 μs | 0.008 | 0.00 | 472 B | NA | -| RawIlgpuCpu | 1024 | Mandelbrot | 485,543.50 μs | 4,226.696 μs | 3,953.654 μs | 4.096 | 0.04 | 176 B | NA | -| RawIlgpuCuda | 1024 | Mandelbrot | 917.05 μs | 2.141 μs | 2.003 μs | 0.008 | 0.00 | 112 B | NA | -| | | | | | | | | | | -| **CSharpSingleThread** | **4096** | **VectorAdd** | **12,926.89 μs** | **79.759 μs** | **74.606 μs** | **1.00** | **0.01** | **-** | **NA** | -| CSharpNativeThreads | 4096 | VectorAdd | 10,622.31 μs | 41.977 μs | 39.265 μs | 0.82 | 0.01 | - | NA | -| KerneliumCpu | 4096 | VectorAdd | 6,103,064.75 μs | 25,386.776 μs | 21,199.107 μs | 472.14 | 3.08 | 672 B | NA | -| KerneliumCuda | 4096 | VectorAdd | 12,268.57 μs | 240.423 μs | 236.127 μs | 0.95 | 0.02 | 528 B | NA | -| RawIlgpuCpu | 4096 | VectorAdd | 6,046,217.83 μs | 14,643.413 μs | 11,432.613 μs | 467.74 | 2.75 | 224 B | NA | -| RawIlgpuCuda | 4096 | VectorAdd | 11,262.13 μs | 4.813 μs | 4.266 μs | 0.87 | 0.00 | 80 B | NA | -| | | | | | | | | | | -| **CSharpSingleThread** | **4096** | **Mandelbrot** | **1,862,285.55 μs** | **2,528.853 μs** | **2,365.490 μs** | **1.000** | **0.00** | **-** | **NA** | -| CSharpNativeThreads | 4096 | Mandelbrot | 366,304.24 μs | 6,678.613 μs | 6,559.291 μs | 0.197 | 0.00 | - | NA | -| KerneliumCpu | 4096 | Mandelbrot | 7,817,549.57 μs | 65,845.009 μs | 61,591.463 μs | 4.198 | 0.03 | 536 B | NA | -| KerneliumCuda | 4096 | Mandelbrot | 12,150.44 μs | 18.062 μs | 16.895 μs | 0.007 | 0.00 | 440 B | NA | -| RawIlgpuCpu | 4096 | Mandelbrot | 7,933,003.88 μs | 33,490.785 μs | 27,966.322 μs | 4.260 | 0.02 | 176 B | NA | -| RawIlgpuCuda | 4096 | Mandelbrot | 12,103.77 μs | 8.284 μs | 7.344 μs | 0.006 | 0.00 | 80 B | NA | +| Method | Side | Workload | Mean | Error | StdDev | Median | Ratio | RatioSD | Gen0 | Allocated | Alloc Ratio | +|---------------------------------- |----- |----------- |----------------:|--------------:|--------------:|----------------:|-------:|--------:|-------:|----------:|------------:| +| **KerneliumCpuSerialBatches** | **256** | **VectorAdd** | **25,143.17 μs** | **415.287 μs** | **388.460 μs** | **24,896.04 μs** | **583.72** | **8.83** | **-** | **6816 B** | **NA** | +| KerneliumCpuAsyncBatches | 256 | VectorAdd | 25,164.91 μs | 172.958 μs | 161.785 μs | 25,209.62 μs | 584.23 | 3.86 | - | 8624 B | NA | +| KerneliumCpuThreadedAsyncBatches | 256 | VectorAdd | 25,044.91 μs | 58.437 μs | 54.662 μs | 25,037.98 μs | 581.44 | 1.79 | - | 8504 B | NA | +| KerneliumCudaSerialBatches | 256 | VectorAdd | 108.67 μs | 0.319 μs | 0.298 μs | 108.67 μs | 2.52 | 0.01 | 0.7324 | 6368 B | NA | +| KerneliumCudaAsyncBatches | 256 | VectorAdd | 125.71 μs | 1.237 μs | 1.033 μs | 125.98 μs | 2.92 | 0.02 | 0.7324 | 8088 B | NA | +| KerneliumCudaThreadedAsyncBatches | 256 | VectorAdd | 161.86 μs | 3.198 μs | 8.424 μs | 162.70 μs | 3.76 | 0.19 | 0.7324 | 7968 B | NA | +| CSharpSingleThread | 256 | VectorAdd | 43.07 μs | 0.119 μs | 0.100 μs | 43.07 μs | 1.00 | 0.00 | - | - | NA | +| CSharpNativeThreads | 256 | VectorAdd | 180.41 μs | 1.186 μs | 1.110 μs | 180.59 μs | 4.19 | 0.03 | - | - | NA | +| KerneliumCpu | 256 | VectorAdd | 27,687.06 μs | 38.990 μs | 36.472 μs | 27,699.91 μs | 642.78 | 1.65 | - | 3584 B | NA | +| KerneliumCuda | 256 | VectorAdd | 94.84 μs | 0.342 μs | 0.320 μs | 94.71 μs | 2.20 | 0.01 | 0.3662 | 3296 B | NA | +| RawIlgpuCpu | 256 | VectorAdd | 23,999.29 μs | 131.173 μs | 122.699 μs | 24,024.33 μs | 557.17 | 3.03 | - | 224 B | NA | +| RawIlgpuCuda | 256 | VectorAdd | 90.73 μs | 0.348 μs | 0.325 μs | 90.80 μs | 2.11 | 0.01 | - | 128 B | NA | +| | | | | | | | | | | | | +| **KerneliumCpuSerialBatches** | **256** | **Mandelbrot** | **32,186.78 μs** | **139.065 μs** | **123.278 μs** | **32,213.39 μs** | **4.37** | **0.02** | **-** | **6048 B** | **NA** | +| KerneliumCpuAsyncBatches | 256 | Mandelbrot | 31,525.80 μs | 95.858 μs | 84.975 μs | 31,500.06 μs | 4.28 | 0.01 | - | 7856 B | NA | +| KerneliumCpuThreadedAsyncBatches | 256 | Mandelbrot | 31,865.04 μs | 152.663 μs | 135.331 μs | 31,818.53 μs | 4.33 | 0.02 | - | 7736 B | NA | +| KerneliumCudaSerialBatches | 256 | Mandelbrot | 203.75 μs | 0.802 μs | 0.751 μs | 203.93 μs | 0.03 | 0.00 | 0.4883 | 5680 B | NA | +| KerneliumCudaAsyncBatches | 256 | Mandelbrot | 146.63 μs | 1.741 μs | 1.543 μs | 146.86 μs | 0.02 | 0.00 | 0.7324 | 7400 B | NA | +| KerneliumCudaThreadedAsyncBatches | 256 | Mandelbrot | 184.73 μs | 3.665 μs | 5.918 μs | 181.14 μs | 0.03 | 0.00 | 0.7324 | 7280 B | NA | +| CSharpSingleThread | 256 | Mandelbrot | 7,360.36 μs | 2.213 μs | 1.962 μs | 7,360.17 μs | 1.00 | 0.00 | - | - | NA | +| CSharpNativeThreads | 256 | Mandelbrot | 1,743.83 μs | 7.004 μs | 6.209 μs | 1,746.17 μs | 0.24 | 0.00 | - | - | NA | +| KerneliumCpu | 256 | Mandelbrot | 31,012.04 μs | 91.085 μs | 85.201 μs | 31,000.01 μs | 4.21 | 0.01 | - | 3056 B | NA | +| KerneliumCuda | 256 | Mandelbrot | 118.98 μs | 0.129 μs | 0.108 μs | 118.96 μs | 0.02 | 0.00 | 0.2441 | 2944 B | NA | +| RawIlgpuCpu | 256 | Mandelbrot | 32,375.76 μs | 642.852 μs | 536.811 μs | 32,186.52 μs | 4.40 | 0.07 | - | 176 B | NA | +| RawIlgpuCuda | 256 | Mandelbrot | 130.51 μs | 2.583 μs | 5.725 μs | 130.23 μs | 0.02 | 0.00 | - | 112 B | NA | +| | | | | | | | | | | | | +| **KerneliumCpuSerialBatches** | **1024** | **VectorAdd** | **393,101.61 μs** | **7,481.504 μs** | **13,103.251 μs** | **388,922.60 μs** | **563.64** | **18.74** | **-** | **6816 B** | **NA** | +| KerneliumCpuAsyncBatches | 1024 | VectorAdd | 399,094.45 μs | 7,803.177 μs | 13,666.637 μs | 394,500.60 μs | 572.23 | 19.53 | - | 8624 B | NA | +| KerneliumCpuThreadedAsyncBatches | 1024 | VectorAdd | 386,986.99 μs | 4,397.706 μs | 3,898.452 μs | 387,338.95 μs | 554.87 | 5.96 | - | 8632 B | NA | +| KerneliumCudaSerialBatches | 1024 | VectorAdd | 929.65 μs | 13.236 μs | 12.381 μs | 928.67 μs | 1.33 | 0.02 | - | 6368 B | NA | +| KerneliumCudaAsyncBatches | 1024 | VectorAdd | 939.44 μs | 15.731 μs | 15.450 μs | 940.21 μs | 1.35 | 0.02 | - | 8088 B | NA | +| KerneliumCudaThreadedAsyncBatches | 1024 | VectorAdd | 1,010.48 μs | 20.039 μs | 46.044 μs | 1,002.93 μs | 1.45 | 0.07 | - | 7968 B | NA | +| CSharpSingleThread | 1024 | VectorAdd | 697.45 μs | 3.492 μs | 3.267 μs | 697.67 μs | 1.00 | 0.01 | - | - | NA | +| CSharpNativeThreads | 1024 | VectorAdd | 309.42 μs | 2.455 μs | 2.296 μs | 309.92 μs | 0.44 | 0.00 | - | - | NA | +| KerneliumCpu | 1024 | VectorAdd | 380,232.69 μs | 5,370.961 μs | 4,761.217 μs | 378,257.25 μs | 545.19 | 7.04 | - | 3584 B | NA | +| KerneliumCuda | 1024 | VectorAdd | 804.24 μs | 0.492 μs | 0.411 μs | 804.29 μs | 1.15 | 0.01 | - | 3360 B | NA | +| RawIlgpuCpu | 1024 | VectorAdd | 376,338.52 μs | 1,345.208 μs | 1,258.309 μs | 376,545.40 μs | 539.61 | 3.01 | - | 224 B | NA | +| RawIlgpuCuda | 1024 | VectorAdd | 802.39 μs | 1.070 μs | 0.948 μs | 801.98 μs | 1.15 | 0.01 | - | 80 B | NA | +| | | | | | | | | | | | | +| **KerneliumCpuSerialBatches** | **1024** | **Mandelbrot** | **491,560.17 μs** | **2,521.490 μs** | **2,358.603 μs** | **490,460.90 μs** | **4.190** | **0.02** | **-** | **6048 B** | **NA** | +| KerneliumCpuAsyncBatches | 1024 | Mandelbrot | 495,259.71 μs | 1,475.676 μs | 1,380.349 μs | 495,241.40 μs | 4.222 | 0.01 | - | 7984 B | NA | +| KerneliumCpuThreadedAsyncBatches | 1024 | Mandelbrot | 481,635.55 μs | 1,164.797 μs | 1,032.562 μs | 481,142.70 μs | 4.106 | 0.01 | - | 7864 B | NA | +| KerneliumCudaSerialBatches | 1024 | Mandelbrot | 1,064.40 μs | 2.140 μs | 1.787 μs | 1,063.99 μs | 0.009 | 0.00 | - | 5680 B | NA | +| KerneliumCudaAsyncBatches | 1024 | Mandelbrot | 1,050.26 μs | 1.413 μs | 1.253 μs | 1,050.42 μs | 0.009 | 0.00 | - | 7400 B | NA | +| KerneliumCudaThreadedAsyncBatches | 1024 | Mandelbrot | 1,073.68 μs | 2.337 μs | 2.186 μs | 1,072.73 μs | 0.009 | 0.00 | - | 7280 B | NA | +| CSharpSingleThread | 1024 | Mandelbrot | 117,304.88 μs | 175.400 μs | 164.069 μs | 117,248.94 μs | 1.000 | 0.00 | - | - | NA | +| CSharpNativeThreads | 1024 | Mandelbrot | 22,558.98 μs | 379.719 μs | 355.190 μs | 22,489.46 μs | 0.192 | 0.00 | - | - | NA | +| KerneliumCpu | 1024 | Mandelbrot | 499,559.21 μs | 397.306 μs | 310.190 μs | 499,665.75 μs | 4.259 | 0.01 | - | 3184 B | NA | +| KerneliumCuda | 1024 | Mandelbrot | 918.57 μs | 0.418 μs | 0.371 μs | 918.58 μs | 0.008 | 0.00 | - | 2944 B | NA | +| RawIlgpuCpu | 1024 | Mandelbrot | 478,899.15 μs | 1,788.599 μs | 1,493.561 μs | 478,481.70 μs | 4.083 | 0.01 | - | 176 B | NA | +| RawIlgpuCuda | 1024 | Mandelbrot | 914.15 μs | 0.357 μs | 0.316 μs | 914.09 μs | 0.008 | 0.00 | - | 80 B | NA | +| | | | | | | | | | | | | +| **KerneliumCpuSerialBatches** | **4096** | **VectorAdd** | **5,973,283.75 μs** | **6,219.444 μs** | **5,513.375 μs** | **5,972,549.40 μs** | **484.70** | **0.97** | **-** | **6816 B** | **NA** | +| KerneliumCpuAsyncBatches | 4096 | VectorAdd | 6,006,845.99 μs | 6,437.914 μs | 5,707.044 μs | 6,006,379.45 μs | 487.42 | 0.98 | - | 8752 B | NA | +| KerneliumCpuThreadedAsyncBatches | 4096 | VectorAdd | 5,969,399.15 μs | 10,797.780 μs | 9,016.635 μs | 5,966,202.70 μs | 484.38 | 1.12 | - | 9568 B | NA | +| KerneliumCudaSerialBatches | 4096 | VectorAdd | 14,433.31 μs | 35.022 μs | 32.759 μs | 14,441.41 μs | 1.17 | 0.00 | - | 6368 B | NA | +| KerneliumCudaAsyncBatches | 4096 | VectorAdd | 11,435.42 μs | 5.615 μs | 5.252 μs | 11,435.79 μs | 0.93 | 0.00 | - | 8089 B | NA | +| KerneliumCudaThreadedAsyncBatches | 4096 | VectorAdd | 14,477.85 μs | 10.955 μs | 9.711 μs | 14,480.58 μs | 1.17 | 0.00 | - | 7968 B | NA | +| CSharpSingleThread | 4096 | VectorAdd | 12,323.76 μs | 24.372 μs | 22.797 μs | 12,331.72 μs | 1.00 | 0.00 | - | - | NA | +| CSharpNativeThreads | 4096 | VectorAdd | 10,302.41 μs | 20.143 μs | 17.856 μs | 10,299.82 μs | 0.84 | 0.00 | - | - | NA | +| KerneliumCpu | 4096 | VectorAdd | 6,017,982.44 μs | 3,619.099 μs | 3,208.237 μs | 6,018,525.50 μs | 488.32 | 0.91 | - | 3584 B | NA | +| KerneliumCuda | 4096 | VectorAdd | 11,278.65 μs | 2.067 μs | 1.726 μs | 11,278.88 μs | 0.92 | 0.00 | - | 3232 B | NA | +| RawIlgpuCpu | 4096 | VectorAdd | 6,402,093.02 μs | 6,657.501 μs | 6,227.431 μs | 6,400,277.50 μs | 519.49 | 1.05 | - | 224 B | NA | +| RawIlgpuCuda | 4096 | VectorAdd | 11,272.26 μs | 3.675 μs | 3.257 μs | 11,271.73 μs | 0.91 | 0.00 | - | 80 B | NA | +| | | | | | | | | | | | | +| **KerneliumCpuSerialBatches** | **4096** | **Mandelbrot** | **7,728,590.81 μs** | **10,257.561 μs** | **8,008.429 μs** | **7,726,215.75 μs** | **4.154** | **0.00** | **-** | **6048 B** | **NA** | +| KerneliumCpuAsyncBatches | 4096 | Mandelbrot | 7,828,702.66 μs | 7,048.262 μs | 6,248.101 μs | 7,829,691.20 μs | 4.208 | 0.00 | - | 9048 B | NA | +| KerneliumCpuThreadedAsyncBatches | 4096 | Mandelbrot | 7,708,012.56 μs | 5,618.266 μs | 4,980.446 μs | 7,706,790.10 μs | 4.143 | 0.00 | - | 7864 B | NA | +| KerneliumCudaSerialBatches | 4096 | Mandelbrot | 12,284.61 μs | 4.995 μs | 4.672 μs | 12,283.59 μs | 0.007 | 0.00 | - | 5680 B | NA | +| KerneliumCudaAsyncBatches | 4096 | Mandelbrot | 12,271.85 μs | 5.335 μs | 4.990 μs | 12,269.74 μs | 0.007 | 0.00 | - | 7400 B | NA | +| KerneliumCudaThreadedAsyncBatches | 4096 | Mandelbrot | 12,352.77 μs | 4.315 μs | 4.036 μs | 12,352.49 μs | 0.007 | 0.00 | - | 7280 B | NA | +| CSharpSingleThread | 4096 | Mandelbrot | 1,860,334.46 μs | 613.866 μs | 544.177 μs | 1,860,186.90 μs | 1.000 | 0.00 | - | - | NA | +| CSharpNativeThreads | 4096 | Mandelbrot | 333,789.00 μs | 4,254.533 μs | 3,979.693 μs | 333,381.60 μs | 0.179 | 0.00 | - | - | NA | +| KerneliumCpu | 4096 | Mandelbrot | 7,698,405.59 μs | 5,310.857 μs | 4,434.806 μs | 7,697,857.20 μs | 4.138 | 0.00 | - | 3184 B | NA | +| KerneliumCuda | 4096 | Mandelbrot | 12,105.97 μs | 4.515 μs | 4.003 μs | 12,105.51 μs | 0.007 | 0.00 | - | 2881 B | NA | +| RawIlgpuCpu | 4096 | Mandelbrot | 7,671,824.29 μs | 6,265.592 μs | 5,232.053 μs | 7,672,754.00 μs | 4.124 | 0.00 | - | 176 B | NA | +| RawIlgpuCuda | 4096 | Mandelbrot | 12,205.88 μs | 5.586 μs | 5.225 μs | 12,205.48 μs | 0.007 | 0.00 | - | 80 B | NA | diff --git a/llms.txt b/llms.txt index fa96aec..bfdf5c3 100644 --- a/llms.txt +++ b/llms.txt @@ -4,11 +4,11 @@ ## Install and check the version -- `dotnet add package Kernelium --version 0.2.0-preview.1` installs the current preview with the APIs documented below. +- This file documents Kernelium 0.3.0. Install it with `dotnet add package Kernelium --version 0.3.0`. To build against the checkout, add a project reference to `Kernelium/Kernelium.csproj`. ## Quickstart -Use this as `Program.cs` in a .NET 10 console app. The CPU backend runs without a GPU. +Use this as `Program.cs` in a .NET 10 console app. Use the CPU backend for development and debugging on machines without a GPU. ```csharp using ILGPU; @@ -38,19 +38,42 @@ static void DoubleValues(ArrayView input, ArrayView output) - `GenerateKernel` compiles eagerly by default. Use `precompile: false` to defer compilation. `Execute` returns after the kernel and any copy-back complete. - `kernel.Execute(count, ...)` sizes a 1D launch. `kernel.Execute2D(width, height, ...)` sizes a 2D launch. Pass dimensions again as kernel arguments if the kernel needs them, for example `kernel.Execute2D(width, height, width, height, input, output)`. - Launches may round up to a full group. Guard each global index against the logical extent. For a flat row-major image, guard both `x` and `y` before indexing with `y * width + x`. -- Use the `KernelConfig` overload for explicit grid and group dimensions. Kernel methods use ILGPU's supported subset of C# and write results through `ArrayView`. +- 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. + +## Async execution + +- Call `kernel.ExecuteAsync(workItems, ...)`, `kernel.ExecuteAsync(config, ...)`, or `kernel.Execute2DAsync(width, height, ...)`. The returned task reports execution errors and completes successfully after the kernel, host copy-back, and temporary resource cleanup. +- Keep borrowed host inputs stable through task completion. You can read and share input-only arrays. Leave writable arrays untouched until every pending use completes. Passing the same array in multiple argument positions creates a separate device allocation for each position. +- Kernelium orders conflicting synchronous and async operations, including buffer uploads and downloads, by submission. Host arrays conflict by reference when either use writes, including across GPU instances. Device buffers, slices, and views nested in structs conflict by backing allocation. +- Multiple host threads can submit work on every backend. CUDA and OpenCL use two async streams per GPU and may overlap independent workloads. ILGPU runs one kernel at a time per CPU accelerator. + +Using the quickstart kernel and stable input: + +```csharp +var first = new int[input.Length]; +var second = new int[input.Length]; +await Task.WhenAll( + kernel.ExecuteAsync(first.Length, ArrayArgument.Input(input), ArrayArgument.Output(first)), + kernel.ExecuteAsync(second.Length, ArrayArgument.Input(input), ArrayArgument.Output(second))); +``` ## Transfers and resource ownership - A plain `T[]` gets a temporary device buffer, an upload, and a copy-back on success. With `ArrayArgument.Input(array)` only the upload happens. With `ArrayArgument.Output(array)` only the copy-back happens, so the kernel needs to initialize the entire output. -- For repeated launches, use `using var source = gpu.Upload(input);` and `using var destination = gpu.Allocate(output.Length);`. Pass both buffers to `Execute` and call `destination.Download(output)` when the host needs the result. -- Use buffers with the GPU that created them and dispose them before that GPU. Keep intermediate results on the device across launches to avoid repeated allocations and transfers. +- 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. +- 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. ## ILGPU interop - `gpu.Device` reports the actual selected backend and device name, along with memory size, grid and group limits, and backend capabilities. - `gpu.Accelerator` is the underlying ILGPU accelerator. The `GPU` instance owns it. Dispose any buffers and streams you create before disposing `GPU`. -- Pass compatible ILGPU views from the same accelerator to Kernelium. Kernelium launches on the default stream. Synchronize dependent work submitted to a custom stream before launching a Kernelium kernel that uses its results. +- 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. + +## Benchmarks + +- The workspace project at `examples/Kernelium.Benchmarks` measures serial, async, and dedicated-thread async submission of two batches with the same readbacks. From the project directory, run `dotnet run -c Release -- --filter "*Batches"`. Use `--gpu-only` for the CUDA and GPU-backed OpenCL suite, or `--cuda-async-throughput` to compare CUDA serial and async execution with device-resident data. The November 28 release report covers 72 cases, including CPU and CUDA batch submission with output readback and synchronous comparisons against native C# and raw ILGPU. 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