Search code examples
f#aleagpu

Pass Alea GPU kernel a function


Is this possible in F# with Alea GPU?

Declare a function:

let my_function = fun a b -> a + b

Pass the kernel that function, and use it within the kernel:

let result = my_function 5 9

I understand that an alternative is to simply statically declare the function like:

[<ReflectedDefinition>]
let my_function a b =
    a + b

But I want to be able to change my_function based on the parameters of the program.

For example:

[<ReflectedDefinition>]
let kernel (a:int) (adder:int->int) =
    let result <- adder a

let transformKernel = <@ kernel @> |> Compiler.makeKernel

let add_num b =
    fun (a:int) ->
        a + b

let run num1 num2 =
    let adder = add_num num2
    let gpu = Gpu.Default
    let num1Gpu = gpu.Allocate(num1)
    let adderGpu = gpu.Allocate(adder)
    let lp = LaunchParam(1, 1)
    gpu.Launch transformKernel lp num1Gpu adderGpu
    // return result


let my_result = run 3 7
// my_result should be 10

Solution

  • I found a solution to this in the Alea GPU sample gallery. The simplest example I could see of this is the F# Generic Transform sample. It uses code quotations to compile kernels based on any given function of some specified type (e.g. int -> int -> int)