diff --git a/Project.toml b/Project.toml index 9c8cda6..cbe6a97 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "GPUToolbox" uuid = "096a3bc2-3ced-46d0-87f4-dd12716f4bfc" -version = "3.7.0" +version = "3.8.0" [compat] julia = "1.10" diff --git a/src/GPUToolbox.jl b/src/GPUToolbox.jl index 3386be4..b476716 100644 --- a/src/GPUToolbox.jl +++ b/src/GPUToolbox.jl @@ -8,5 +8,6 @@ include("threading.jl") include("memoization.jl") include("synchronization.jl") include("overlays.jl") +include("launch.jl") end # module GPUToolbox diff --git a/src/launch.jl b/src/launch.jl new file mode 100644 index 0000000..be531c5 --- /dev/null +++ b/src/launch.jl @@ -0,0 +1,144 @@ +# helpers for implementing kernel launch macros like `@cuda` + +if VERSION >= v"1.11.0-DEV.469" + eval(Expr(:public, :parse_launch_macro, :partition_kwargs)) +end + +""" + parse_launch_macro(ex::Tuple; name::String, options=(:launch,)) + +Parse the arguments `ex` of a kernel launch macro, like `@cuda threads=n kernel(a, b)`: +keyword arguments followed by a function call. `name` is the name of the macro, used in +error messages, and `options` lists the keywords that configure the macro itself rather +than the kernel's compilation or launch. + +Returns a `NamedTuple` with these fields, all expressions to be used in the macro's +expansion (they are not escaped): + +- `bindings`: a block that evaluates each argument of the call once, binding it to a + fresh variable. Include it in the expansion before using `args` or `roots`. +- `callee`: the function being called, as written. It is not evaluated by `bindings`, so + the macro decides when to do so. +- `args`: the bound arguments, to be used as the arguments of a call. A splatted argument + `xs...` becomes `var...`, and is iterated anew at each use. +- `roots`: the variables bound to the arguments, to keep alive with `GC.@preserve`. +- `options`: a `Dict` from the keywords in `options` that were written out to their + values, as written. The macro has to validate these itself, e.g. that a value is a + literal `Bool`. Each can only be written once. +- `kwargs`: the remaining keyword arguments, as `key=value` expressions or splats `x...`, + in the order they were written, with `key` shorthand expanded to `key=key`. + +The names in a splat are only known at run time, so the macro should route all of `kwargs` +then, with [`partition_kwargs`](@ref): build one `NamedTuple` from them, which evaluates +them and resolves repeated names in order like the keyword arguments of a function call, +and partition it. A splat can contain an option, which the macro has to reject: + +```julia +macro mylaunch(ex...) + p = GPUToolbox.parse_launch_macro(ex; name="@mylaunch", options=(:launch,)) + launch = get(p.options, :launch, true) + launch isa Bool || throw(ArgumentError("`launch` to @mylaunch should be a literal Bool")) + esc(quote + let + \$(p.bindings) + options, launch_kwargs, compiler_kwargs = + \$(GPUToolbox.partition_kwargs)((; \$(p.kwargs...)), (:launch,), (:threads, :blocks)) + isempty(options) || throw(ArgumentError("options to @mylaunch cannot be splatted")) + args = (\$(p.args...),) + kernel = \$compile(\$(p.callee), args...; compiler_kwargs...) + \$launch && kernel(args...; launch_kwargs...) + kernel + end + end) +end +``` + +Here, `compile` stands for the back-end's compiler. A real macro should use variables made +with `gensym` instead of names like `options`, as the expansion is evaluated in the +caller's scope. Interpolate functions, like `partition_kwargs` above, so +that the caller doesn't need to have imported them. +""" +function parse_launch_macro(ex::Tuple; name::String, options=(:launch,)) + isempty(ex) && throw(ArgumentError("$name expects a function call")) + call = ex[end] + Meta.isexpr(call, :call) && !isempty(call.args) || + throw(ArgumentError("the last argument to $name should be a function call")) + for arg in call.args[2:end] + if Meta.isexpr(arg, :parameters) || Meta.isexpr(arg, :kw) + throw(ArgumentError("keyword arguments are written before the call, " * + "as in `$name key=value f(args...)`")) + end + end + + parsed_options = Dict{Symbol,Any}() + kwargs = Any[] + for kwarg in ex[1:end-1] + if kwarg isa Symbol + kwarg = :($kwarg = $kwarg) + elseif Meta.isexpr(kwarg, :(...), 1) + push!(kwargs, kwarg) + continue + end + if !Meta.isexpr(kwarg, :(=), 2) || !(kwarg.args[1] isa Symbol) + throw(ArgumentError("invalid keyword argument '$kwarg' to $name")) + end + key, val = kwarg.args + if key in options + haskey(parsed_options, key) && + throw(ArgumentError("keyword argument '$key' to $name is repeated")) + parsed_options[key] = val + else + push!(kwargs, kwarg) + end + end + + bindings = Expr(:block) + args = Any[] + roots = Symbol[] + for arg in call.args[2:end] + splat = Meta.isexpr(arg, :(...), 1) + var = gensym(:arg) + push!(bindings.args, :($var = $(splat ? arg.args[1] : arg))) + push!(roots, var) + push!(args, splat ? :($var...) : var) + end + + return (; bindings, callee=call.args[1], args, roots, options=parsed_options, kwargs) +end + +""" + partition_kwargs(kwargs, groups...) -> (group_1::NamedTuple, ..., rest::NamedTuple) + +Partition keyword arguments by name: each of `groups`, a collection of `Symbol`s, claims +the keyword arguments it lists that an earlier group did not, and `rest` holds those that +no group claims. Each result keeps the order of `kwargs`, which can be a `NamedTuple` or +anything else that can be splatted as keyword arguments, like the `kwargs...` of a +function. + +When the type of `kwargs` is a concrete `NamedTuple`, and the groups are tuples whose +values are known to the compiler, like constants, the partition happens at compile time: +the call is type stable and doesn't allocate. Use tuples rather than vectors for groups +used when launching a kernel. + +```jldoctest +julia> GPUToolbox.partition_kwargs((; threads=32, maxregs=16, blocks=4), (:threads, :blocks)) +((threads = 32, blocks = 4), (maxregs = 16,)) +``` +""" +@inline partition_kwargs(kwargs, groups...) = partition_named((; kwargs...), map(Tuple, groups)...) + +@inline partition_named(rest::NamedTuple) = (rest,) +@inline function partition_named(kwargs::NamedTuple{names}, group::Tuple, + groups::Tuple...) where {names} + claimed = select_names(names, group, true) + rest = select_names(names, group, false) + return (NamedTuple{claimed}(kwargs), partition_named(NamedTuple{rest}(kwargs), groups...)...) +end + +# the names in `names` that are, or with `keep=false` are not, in `group`. foldable, so +# that a partition by constant groups happens at compile time. +Base.@assume_effects :foldable function select_names(names::Tuple{Vararg{Symbol}}, + group::Tuple{Vararg{Symbol}}, + keep::Bool) + return filter(name -> (name in group) == keep, names) +end diff --git a/test/launch.jl b/test/launch.jl new file mode 100644 index 0000000..d4be1a6 --- /dev/null +++ b/test/launch.jl @@ -0,0 +1,66 @@ +# a minimal launch macro, which calls the function and returns the keyword arguments +macro test_launch(ex...) + p = GPUToolbox.parse_launch_macro(ex; name="@test_launch") + esc(quote + let + $(p.bindings) + ($(p.callee)($(p.args...)), (; $(p.kwargs...))) + end + end) +end + +@testset "parse_launch_macro" begin + parse(ex...; kwargs...) = GPUToolbox.parse_launch_macro(ex; name="@test_launch", kwargs...) + + p = parse(:(launch = false), :threads, :(blocks = 2), :(config...), :(f(x, ys...))) + @test p.callee == :f + @test p.options == Dict(:launch => false) + @test p.kwargs == [:(threads = threads), :(blocks = 2), :(config...)] + x, ys = p.roots + @test p.bindings.args == [:($x = x), :($ys = ys)] + @test p.args == [x, :($ys...)] + + # options are only the listed ones, as written + p = parse(:(launch = true), :(backend = b()), :(f()); options=(:backend,)) + @test p.options == Dict(:backend => :(b())) + @test p.kwargs == [:(launch = true)] + @test isempty(p.args) && isempty(p.roots) && isempty(p.bindings.args) + + @test_throws "should be a function call" parse(:(threads = 1), :x) + @test_throws "expects a function call" parse() + @test_throws "invalid keyword argument '1'" parse(1, :(f())) + @test_throws "invalid keyword argument 'a.b = 1'" parse(:(a.b = 1), :(f())) + @test_throws "'launch' to @test_launch is repeated" parse(:(launch = true), :(launch = false), :(f())) + @test_throws "keyword arguments are written before the call" parse(:(f(x; y=1))) + @test_throws "keyword arguments are written before the call" parse(:(f(x, y=1))) + @test_throws "should be a function call" parse(Expr(:call)) + + # the expansion evaluates each argument once, in order + order = [] + config = (; b=2) + result = @test_launch a=(push!(order, :a); 1) config... (push!(order, :f); tuple)( + (push!(order, :x); 1), (push!(order, :ys); (2, 3))...) + @test result == ((1, 2, 3), (; a=1, b=2)) + @test order == [:x, :ys, :f, :a] +end + +@testset "partition_kwargs" begin + nt = (; c=3, a=1, d=4, b=2) + @test GPUToolbox.partition_kwargs(nt) === (nt,) + @test GPUToolbox.partition_kwargs(nt, (:b, :a)) === ((; a=1, b=2), (; c=3, d=4)) + @test GPUToolbox.partition_kwargs(nt, (:a, :x), (:a, :c)) === ((; a=1), (; c=3), (; d=4, b=2)) + @test GPUToolbox.partition_kwargs(nt, ()) === ((;), nt) + + # type stable and allocation-free for NamedTuples and constant groups + partition(nt) = GPUToolbox.partition_kwargs(nt, (:a,), (:b, :c)) + @inferred partition(nt) + partition!(r, nt) = (r[] = partition(nt); nothing) + r = Ref{typeof(partition(nt))}() + partition!(r, nt) + @test @allocated(partition!(r, nt)) == 0 + + # other collections of keyword arguments and groups + kw(; kwargs...) = kwargs + @test GPUToolbox.partition_kwargs(kw(; a=1, b=2), [:b]) === ((; b=2), (; a=1)) + @test GPUToolbox.partition_kwargs(Dict(:a => 1, :b => 2), [:a]) == ((; a=1), (; b=2)) +end diff --git a/test/runtests.jl b/test/runtests.jl index f42c71c..22820df 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -977,4 +977,5 @@ using IOCapture end include("synchronization.jl") + include("launch.jl") end