Skip to content

[QUESTION]: How can I define kernel which depends generic specialized method? #1427

@aka-nse

Description

@aka-nse

Question

Hello.

I want to define a kernel which uses generic specialized method, but it throws InternalCompilerException:
(Please note that GenericSin is external API so that it cannot be migrate closed generic kernel pattern e.g. GenericKernel sample)

using ILGPU;
using ILGPU.Runtime;

using var context = Context.CreateDefault();
using var accelerator = context.GetPreferredDevice(false).CreateAccelerator(context);

// OK: non generic 
var kernel1 = accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<float>, ArrayView<float>>(Kernel1);

// NG: reference to System.Type is denied
var kernel2 = accelerator.LoadAutoGroupedStreamKernel<Index1D, ArrayView<float>, ArrayView<float>>(Kernel2<float>);

static void Kernel1(Index1D index, ArrayView<float> x, ArrayView<float> ans)
{
    ans[index] = MathF.Sin(x[index]);
}


static void Kernel2<T>(Index1D index, ArrayView<T> x, ArrayView<T> ans)
    where T : unmanaged
{
    ans[index] = GenericSin(x[index]);
}

static T GenericSin<T>(T x)
    where T : unmanaged
{
    if (typeof(T) == typeof(float))
        return Unsafe.BitCast<float, T>(MathF.Sin(Unsafe.BitCast<T, float>(x)));
    else if (typeof(T) == typeof(double))
        return Unsafe.BitCast<double, T>(Math.Cos(Unsafe.BitCast<T, double>(x)));
    else
        throw new NotSupportedException();
}

I want to implement any of following technique:

  • defines method call interception from GenericSin<float> to MyGenericSin_float
  • rewrites IL of GenericSin<float> using System.Reflection.Emit APIs and load kernel with its IL stream directly

Sorry because this is likely an edge case, but I would be grateful if you could provide guidance if possible.

Environment

  • ILGPU version: [1.5.3]
  • .NET version: [.NET 9]
  • Operating system: [Windows 11]
  • Hardware (if GPU-related): [NVIDIA GeForce GTX 4070 Ti]

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions