Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion Kernelium.Test/GPUBufferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace Kernelium.Test
{
[TestFixture]
internal static class GPUBufferTests
public static class GPUBufferTests
{
private static GPU CreateGpu() => new(new() { HardwareType = HardwareType.Cpu });

Expand Down Expand Up @@ -145,5 +145,43 @@ public static void KernelRejectsBufferFromDifferentAccelerator(bool useView)
kernel.Execute(new KernelConfig(1, 1), useView ? (object)buffer.View : buffer));
Assert.That(buffer.Download(), Is.EqualTo(new[] { 1 }));
}

[Test]
public static void KernelValidatesNestedViewOwnership()
{
using var gpu = CreateGpu();
using var otherGpu = CreateGpu();
using var local = gpu.Upload(new[] { 3 });
using var foreign = otherGpu.Upload(new[] { 7 });
var kernel = gpu.GenerateKernel(IncrementNestedView);
var argument = new NestedView(new BufferView(local.View));

kernel.Execute(1, argument);
Assert.That(local.Download(), Is.EqualTo(new[] { 4 }));

Assert.Throws<ArgumentException>(() =>
kernel.Execute(1, new NestedView(new BufferView(foreign.View))));
Assert.That(foreign.Download(), Is.EqualTo(new[] { 7 }));

local.Dispose();
Assert.Throws<ObjectDisposedException>(() => kernel.Execute(1, argument));
}

private static void IncrementNestedView(NestedView argument)
{
int index = Grid.GlobalIndex.X;
if (index < argument.Buffer.View.Length)
argument.Buffer.View[index]++;
}

public readonly struct NestedView(BufferView buffer)
{
public readonly BufferView Buffer = buffer;
}

public readonly struct BufferView(ArrayView<int> view)
{
public readonly ArrayView<int> View = view;
}
}
}
22 changes: 19 additions & 3 deletions Kernelium.Test/GPUInit.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using ILGPU;
using System;
using System.Collections.Generic;
using System.Text;
using ILGPU.Runtime;

namespace Kernelium.Test
{
Expand All @@ -20,6 +18,24 @@ public static void TryInit()
});
});
}
[Test]
public static void UseSelectedAcceleratorWithKernelium()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var accelerator = gpu.Accelerator;

Assert.That(gpu.Device, Is.SameAs(accelerator.Device));
Assert.That(gpu.Device.AcceleratorType, Is.EqualTo(AcceleratorType.CPU));
Assert.That(gpu.Device.Name, Is.Not.Empty);
Assert.That(gpu.Device.MaxNumThreadsPerGroup, Is.Positive);

using var buffer = accelerator.Allocate1D<int>(4);
var kernel = gpu.GenerateKernel(TestHelper.Fill<int>);
kernel.Execute(4, (ArrayView<int>)buffer.View, 42);

Assert.That(buffer.GetAsArray1D(), Is.All.EqualTo(42));
}

[Test]
public static void TryInitKernel()
{
Expand Down
131 changes: 131 additions & 0 deletions Kernelium.Test/KernelExecution.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using ILGPU;
using ILGPU.Runtime;
using ILGPU.Runtime.Cuda;

namespace Kernelium.Test
Expand All @@ -18,6 +19,17 @@ public static void ExecuteKernel()
kernel.Execute(new KernelConfig(1, 1), 42));
}

[Test]
public static void BothKernelEntryPointsRejectMulticastDelegates()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
Action<ArrayView<int>> kernel = TestHelper.Increment;
kernel += TestHelper.Square;

Assert.Throws<ArgumentException>(() => new Kernel(gpu, kernel));
Assert.Throws<ArgumentException>(() => gpu.GenerateKernel(kernel));
}

[Test]
public static void ExecuteKernelWithoutParameters()
{
Expand All @@ -30,6 +42,50 @@ public static void ExecuteKernelWithoutParameters()
kernel.Execute(new KernelConfig(1, 1)));
}

[TestCase(Enums.HardwareType.Cuda, AcceleratorType.Cuda)]
[TestCase(Enums.HardwareType.OpenCL, AcceleratorType.OpenCL)]
public static void ExecuteParameterlessKernelOnGpu(
Enums.HardwareType hardwareType,
AcceleratorType acceleratorType)
{
using var context = Context.CreateDefault();
if (!context.Devices.Any(device => device.AcceleratorType == acceleratorType))
Assert.Ignore($"{acceleratorType} accelerator unavailable.");

using var gpu = new GPU(new() { HardwareType = hardwareType });
var kernel = gpu.GenerateKernel(TestHelper.NoParameters);
Assert.DoesNotThrow(() => kernel.Execute(1));

gpu.ClearKernelCache();
Assert.DoesNotThrow(() => kernel.Execute(1));

if (acceleratorType == AcceleratorType.OpenCL)
{
var lambda = gpu.GenerateKernel((Action)(static () => { }));
Assert.DoesNotThrow(() => lambda.Execute(1));
}
}

[Test]
public static void ExecuteParameterlessLambda()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel((Action)(static () => { }));

Assert.DoesNotThrow(() => kernel.Execute(1));
}

[Test]
public static void ExecuteRejectsNullArgumentList()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel(TestHelper.NoParameters);

var error = Assert.Throws<ArgumentNullException>(() => kernel.Execute(1, null!));

Assert.That(error!.ParamName, Is.EqualTo("parameters"));
}

[Test]
public static void ExecuteKernelWithArrayView()
{
Expand All @@ -45,6 +101,81 @@ public static void ExecuteKernelWithArrayView()
Assert.That(data, Is.All.EqualTo(4));
}

[Test]
public static void ExecuteWithInputAndOutputArrays()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel(CopyThenClearInput);
int[] input = [3, -4, 9];
int[] output = [-1, -1, -1];

kernel.Execute(input.Length, ArrayArgument.Input(input), ArrayArgument.Output(output));

Assert.That(output, Is.EqualTo(new[] { 3, -4, 9 }));
Assert.That(input, Is.EqualTo(new[] { 3, -4, 9 }));
}

private static void CopyThenClearInput(ArrayView<int> input, ArrayView<int> output)
{
int index = Grid.GlobalIndex.X;
if (index < input.Length)
{
output[index] = input[index];
input[index] = 0;
}
}

[TestCase(19, 23)]
[TestCase(1, 17)]
[TestCase(17, 1)]
public static void Execute2DCoversEveryCoordinate(int width, int height)
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel(DoublePixel);
int[] input = Enumerable.Range(1, width * height).ToArray();
int[] output = new int[input.Length];

kernel.Execute2D(width, height, width, height,
ArrayArgument.Input(input), ArrayArgument.Output(output));

Assert.That(output, Is.EqualTo(input.Select(value => value * 2)));
}

[Test]
public static void CpuRejectsLaunchesWithTooManyPaddedThreads()
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel(TestHelper.NoParameters);

Assert.Throws<ArgumentOutOfRangeException>(() => kernel.Execute2D(131_072, 32_768));

var config = new KernelConfig(new Index3D(1_024, 1_024, 4_096), new Index3D(1, 1, 1));
Assert.Throws<ArgumentOutOfRangeException>(() => kernel.Execute(config));
}

[TestCase(0, 8, "width")]
[TestCase(8, -1, "height")]
public static void Execute2DRejectsNonPositiveDimensions(int width, int height, string parameter)
{
using var gpu = new GPU(new() { HardwareType = Enums.HardwareType.Cpu });
var kernel = gpu.GenerateKernel(DoublePixel, precompile: false);

var error = Assert.Throws<ArgumentOutOfRangeException>(() => kernel.Execute2D(width, height));

Assert.That(error!.ParamName, Is.EqualTo(parameter));
}

private static void DoublePixel(int width, int height, ArrayView<int> input, ArrayView<int> output)
{
int x = Grid.GlobalIndex.X;
int y = Grid.GlobalIndex.Y;
if (x < width && y < height)
{
int offset = y * width + x;
output[offset] = input[offset] * 2;
}
}

[TestCase(1)]
[TestCase(10)]
[TestCase(32)]
Expand Down
27 changes: 27 additions & 0 deletions Kernelium/ArrayArgument.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace Kernelium
{
/// <summary>Controls transfers for a host array passed to a kernel.</summary>
public sealed class ArrayArgument
{
internal Array Data { get; }
internal bool IsInput { get; }

private ArrayArgument(Array data, bool isInput)
{
ArgumentNullException.ThrowIfNull(data);
Data = data;
IsInput = isInput;
}

/// <summary>Uploads the array and leaves its host contents unchanged after execution.</summary>
public static ArrayArgument Input<T>(T[] array) where T : unmanaged =>
new(array, isInput: true);

/// <summary>
/// Downloads the result into the array after execution. The kernel must
/// initialize every element because the original contents are not uploaded.
/// </summary>
public static ArrayArgument Output<T>(T[] array) where T : unmanaged =>
new(array, isInput: false);
}
}
5 changes: 4 additions & 1 deletion Kernelium/Compilation/KernelCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ public ILGPU.Runtime.Kernel GetOrCompile(Delegate kernel)
{
if (!kernelCache.TryGetValue(kernel.Method,out var compiled))
{
MethodInfo method = KernelWrapper.Wrap(kernel.Method);
MethodInfo method = kernel.Method;
// ILGPU 1.5.3's CUDA launcher assumes at least one parameter.
if (accelerator.AcceleratorType == AcceleratorType.Cuda && method.GetParameters().Length == 0)
method = KernelWrapper.WrapForCuda(method);
compiled = accelerator.LoadKernel(method);
kernelCache.Add(kernel.Method, compiled);
}
Expand Down
31 changes: 12 additions & 19 deletions Kernelium/Compilation/KernelWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@ namespace Kernelium.Compilation
{
internal static class KernelWrapper
{
public static MethodInfo Wrap(MethodInfo kernel)
private static readonly ConditionalWeakTable<MethodInfo, MethodInfo> wrappers = new();

public static MethodInfo WrapForCuda(MethodInfo kernel)
{
if (kernel.GetParameters().Length != 0)
return kernel;
if (!kernel.IsStatic)
throw new NotSupportedException(
"CUDA requires a static method for a parameterless kernel. Use a named static method or add a kernel parameter.");

return wrappers.GetValue(kernel, CreateWrapper);
}

private static MethodInfo CreateWrapper(MethodInfo kernel)
{
var assembly = AssemblyBuilder.DefineDynamicAssembly(
new AssemblyName($"Kernelium_{Guid.NewGuid():N}"),
AssemblyBuilderAccess.Run
AssemblyBuilderAccess.RunAndCollect
);
var accessAttribute = typeof(IgnoresAccessChecksToAttribute)
.GetConstructor(new[] { typeof(string) })!;
Expand Down Expand Up @@ -47,20 +55,5 @@ public static MethodInfo Wrap(MethodInfo kernel)

return type.CreateType()!.GetMethod("Execute")!;
}

public static object[] ConvertArguments(MethodInfo kernel, object[] parameters)
{
int expected = kernel.GetParameters().Length;

if (parameters.Length != expected)
throw new ArgumentException(
$"Kernel expects {expected} parameters, " +
$"but {parameters.Length} were provided."
);

if (expected == 0)
return new object[] { 0 };
return parameters;
}
}
}
Loading
Loading