diff --git a/.buildkite/pipeline.yml b/.buildkite/pipeline.yml index 8ae0b79f1..933fa7976 100644 --- a/.buildkite/pipeline.yml +++ b/.buildkite/pipeline.yml @@ -28,9 +28,11 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 echo "--- :julia: Developing CUDA" - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/CUDA.jl main \ + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/CUDA.jl tb/ki-0.5 \ CUDACore CUDATools lib/cusolver lib/curand lib/cublas lib/cufft lib/cusparse lib/cupti lib/nvml lib/custatevec lib/cudnn lib/cutensor lib/cutensornet || exit 3 julia -e 'println("+++ :julia: Running tests") @@ -79,9 +81,11 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 echo "--- :julia: Developing CUDA" - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/CUDA.jl main \ + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/CUDA.jl tb/ki-0.5 \ CUDACore CUDATools lib/cusolver lib/curand lib/cublas lib/cufft lib/cusparse lib/cupti lib/nvml lib/custatevec lib/cudnn lib/cutensor lib/cutensornet || exit 3 julia -e 'println("--- :julia: Adding Enzyme") using Pkg @@ -134,11 +138,13 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 julia -e 'println("--- :julia: Developing AMDGPU") using Pkg Pkg.add(url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="main")' || exit 3 - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/AMDGPU.jl main || exit 3 + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/AMDGPU.jl tb/ki-0.5 || exit 3 julia -e 'println("--- :julia: Adding Enzyme") using Pkg Pkg.add(["Enzyme", "Test"])' || exit 3 @@ -190,9 +196,11 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 echo "--- :julia: Developing Metal" - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/Metal.jl main || exit 3 + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/Metal.jl tb/ki-0.5 || exit 3 julia -e 'println("+++ :julia: Running tests") using Pkg check = joinpath(pwd(), ".buildkite", "check_sources.jl") @@ -237,11 +245,13 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 julia -e 'println("--- :julia: Developing oneAPI") using Pkg Pkg.add(url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="main")' || exit 3 - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/oneAPI.jl main || exit 3 + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/oneAPI.jl tb/ki-0.5 || exit 3 julia -e 'println("+++ :julia: Running tests") using Pkg @@ -288,11 +298,13 @@ steps: using Pkg println("--- :julia: Instantiating project") Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 julia -e 'println("--- :julia: Developing AMDGPU") using Pkg Pkg.add(url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="main")' || exit 3 - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/AMDGPU.jl main || exit 3 + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/AMDGPU.jl tb/ki-0.5 || exit 3 julia -e 'println("+++ :julia: Running tests") using Pkg @@ -339,9 +351,11 @@ steps: julia -e 'println("--- :julia: Instantiating project") using Pkg Pkg.develop([PackageSpec(; name="KernelAbstractions", path=pwd()), - PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))])' || exit 3 + PackageSpec(; name="KernelInterface", path=joinpath(pwd(), "lib", "KernelInterface"))]) + Pkg.add([PackageSpec(; url="https://github.com/JuliaGPU/AcceleratedKernels.jl", rev="tb/ki-0.5"), + PackageSpec(; url="https://github.com/JuliaGPU/GPUArrays.jl", rev="tb/ki-0.5")])' || exit 3 echo "--- :julia: Developing OpenCL" - julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/OpenCL.jl main lib/intrinsics || exit 3 + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/OpenCL.jl tb/ki-0.5 lib/intrinsics || exit 3 julia -e 'println("+++ :julia: Running tests") using Pkg diff --git a/Project.toml b/Project.toml index 76fa02930..4011d6c0e 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "KernelAbstractions" uuid = "63c18a36-062a-441e-b654-da1e3ab1ce7c" -version = "0.10.9" +version = "0.10.10" authors = ["Valentin Churavy and contributors"] [workspace] @@ -55,7 +55,7 @@ Atomix = "1.5" EnzymeCore = "0.8.25" GPUCompiler = "2.24" GPUToolbox = "3.6" -KernelInterface = "0.4.7" +KernelInterface = "0.5" LLVM = "10" LinearAlgebra = "1.6" MacroTools = "0.5" diff --git a/docs/src/index.md b/docs/src/index.md index 2c504a24f..89ad3171e 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -235,6 +235,15 @@ end compiled once). This lets PoCL vectorize kernels better: an axpy over 10⁵ elements on one thread took about 15% longer than a serial loop, rather than 3× (x86) to 7× (Apple M1) as long. `muladd` is computed with fused multiply-adds on CPUs that have them. +- KernelAbstractions now requires KernelInterface 0.5, which only guarantees a sub-group + width to kernels that request one with `sub_group_size = W`, for a `W` in + `KI.sub_group_sizes(backend)`, and removes `KI.sub_group_size(backend)`. KernelAbstractions' + own collectives, such as `@groupreduce`, read the width on the device and need no change, but + code that sizes anything in a `@kernel` from the host width has to request one. See + [Upgrading from KernelInterface 0.4](@ref). +- A kernel can be constructed with a `sub_group_size` keyword, e.g. + `my_kernel(backend, 256; sub_group_size = 16)`, to compile it for a sub-group width from + `KernelInterface.sub_group_sizes(backend)`. See [Launching kernels](@ref). ## Semantic differences diff --git a/docs/src/kernelinterface.md b/docs/src/kernelinterface.md index c1838fb9d..28b0139f9 100644 --- a/docs/src/kernelinterface.md +++ b/docs/src/kernelinterface.md @@ -77,7 +77,7 @@ What a backend implements, at a glance. The docstrings below have the details. | **Capabilities** | | [`supports_float64`](@ref), [`supports_atomics`](@ref), [`supports_unified`](@ref), [`supports_subgroups`](@ref), [`supports_linear_subgroups`](@ref), [`supports_independent_subgroups`](@ref), [`supports_partitionable_subgroups`](@ref) (all `false`), [`supports_shuffle`](@ref) (`false` unless derived from the natively supported types, see its docstring) | | **Compilation** | [`argconvert`](@ref), [`kernel_function`](@ref), [`launch`](@ref) | | | **Device** | [`get_local_id`](@ref), [`get_group_id`](@ref), [`get_local_size`](@ref), [`get_num_groups`](@ref), [`localmemory`](@ref), [`barrier`](@ref) | [`get_global_id`](@ref), [`get_global_size`](@ref) (derived from the primitive queries), [`_print`](@ref KernelInterface._print) (host `print`) | -| **Sub-groups** | if `supports_subgroups`: [`sub_group_size`](@ref), the sub-group queries, [`sub_group_barrier`](@ref), [`sub_group_any`](@ref), [`sub_group_all`](@ref), and [`sub_group_ballot`](@ref) for widths of at most 64; if `supports_shuffle(backend, T)`: [`shfl`](@ref), [`shfl_down`](@ref), [`shfl_up`](@ref), [`shfl_xor`](@ref) for the primitive `T` supported natively, including `UInt32` | [`sub_group_reduce`](@ref), [`sub_group_scan`](@ref), [`sub_group_exclusive_scan`](@ref) (built on the shuffles); the functions with a `width` (built on those without, or on the ballot); shuffles of other primitive types (as `UInt32` or `UInt64` words) and of structs (packed into `UInt32` words) | +| **Sub-groups** | if `supports_subgroups`: the sub-group queries, [`sub_group_barrier`](@ref), [`sub_group_any`](@ref), [`sub_group_all`](@ref), and [`sub_group_ballot`](@ref) for widths of at most 64; if `supports_shuffle(backend, T)`: [`shfl`](@ref), [`shfl_down`](@ref), [`shfl_up`](@ref), [`shfl_xor`](@ref) for the primitive `T` supported natively, including `UInt32`; if kernels can request a width: [`sub_group_sizes`](@ref), and `kernel_function(...; sub_group_size = W)` for every `W` in it | [`sub_group_reduce`](@ref), [`sub_group_scan`](@ref), [`sub_group_exclusive_scan`](@ref) (built on the shuffles); the functions with a `width` (built on those without, or on the ballot); shuffles of other primitive types (as `UInt32` or `UInt64` words) and of structs (packed into `UInt32` words) | Everything else, such as [`zeros`](@ref KernelInterface.zeros), [`ones`](@ref KernelInterface.ones), the launch-keyword handling of [`Kernel`](@ref) and [`@launch`](@ref KernelInterface.@launch), @@ -102,6 +102,26 @@ include(joinpath(pkgdir(KernelInterface), "test", "testsuite.jl")) Testsuite.testsuite(MyBackend(), MyArray) ``` +### Upgrading from KernelInterface 0.4 + +KernelInterface 0.5 no longer promises a sub-group width to kernels that don't request one, +and removes `KI.sub_group_size(backend)`: it throws an error that explains how to migrate, +until KernelInterface 1.0 removes the method too. + +- **Kernel authors**: code that read `W = KI.sub_group_size(backend)` on the host, e.g. for a + `Val(W)` or to size local memory, picks a width from + [`sub_group_sizes(backend)`](@ref sub_group_sizes) instead (`first` of it, if any width + will do), and compiles the kernel with it: `KI.@launch backend sub_group_size=W ...`. If + the list is empty, it needs a variant that reads the width on the device with + [`get_max_sub_group_size`](@ref), as code that only needs it there does anyway. +- **Backend authors**: replace `sub_group_size(backend)` with + [`sub_group_sizes(backend)`](@ref sub_group_sizes), the widths of at most 64 that the + backend can guarantee, the one to suggest first, and implement `kernel_function`'s `sub_group_size` + keyword for them, throwing an `ArgumentError` for other widths. `sub_group_size = nothing` + has to be accepted as no request. Without a request, kernels may now run at a width the + backend chooses per launch. A device that has sub-groups but can't guarantee a width can + now report them, with an empty `sub_group_sizes`. + ## Backend hierarchy Backends subtype [`Backend`](@ref), and everything else in the interface dispatches on @@ -149,9 +169,12 @@ get_global_size ### [Sub-groups](@id ki_subgroups) Sub-groups are optional ([`supports_subgroups`](@ref)). A work-group is divided into -sub-groups of at most `W = `[`sub_group_size(backend)`](@ref sub_group_size) work-items, the -sub-group width. What KernelInterface guarantees, and backends that report sub-group support -have to ensure: +sub-groups of at most `W = `[`get_max_sub_group_size()`](@ref get_max_sub_group_size) +work-items, the sub-group width of the kernel. It is the width the kernel requested when it +was compiled (see [below](@ref ki_subgroup_width)), or else one that the backend chooses for +each launch: the same for all work-items of the launch, but not known on the host, and not +necessarily the same for different kernels or launches. What KernelInterface guarantees, and backends +that report sub-group support have to ensure: - every work-item has a unique `(get_sub_group_id(), get_sub_group_local_id())` pair in its work-group, which doesn't change during the kernel; @@ -208,6 +231,28 @@ of its lanes take. Without independent sub-groups, all sub-groups of the work-gr execute the same communication functions in the same order. The id and size queries can be used anywhere. +#### [Choosing the width](@id ki_subgroup_width) + +A kernel compiled without a request runs at the width the backend picks for the launch, and +reads it on the device with [`get_max_sub_group_size`](@ref). Code that needs the width on the +host, e.g. to size local memory or to pick a `Val` parameter, has to request one from +[`sub_group_sizes(backend)`](@ref sub_group_sizes) with `kernel_function`'s `sub_group_size` +keyword (also accepted by [`KI.@launch`](@ref KernelInterface.@launch)). The docstring of +`sub_group_sizes` has the guarantee and an example. + +Some hardware supports several widths: Intel GPUs run sub-groups of 8, 16 or 32 work-items, +AMD's RDNA GPUs wavefronts of 32 or 64. Which one is fastest depends on the kernel and the +device. A narrower sub-group gives each work-item more registers, so a register-heavy kernel +that spills at 32 can be several times faster at 16, while a kernel that does little work per +work-item can be faster at 32. Without a request, the backend is free to make that choice per +kernel, or even per launch. `sub_group_sizes` can also be empty while sub-groups are +supported, on devices that can't guarantee any width; kernels then have to work with the +width they read on the device. + +A `@kernel` requests a width when it is constructed, `my_kernel(backend, 256; sub_group_size = W)`. +KernelAbstractions' collectives, such as [`@groupreduce`](@ref KernelAbstractions.@groupreduce), +read the width on the device, and work without a request. + !!! note "Kernel languages" The sub-group functions are meant for kernels written against KernelInterface, and for kernel languages built on it. A kernel is either a KernelInterface kernel or a @@ -331,7 +376,7 @@ max_work_group_size launch_configuration max_work_group_dims max_num_groups -sub_group_size +sub_group_sizes multiprocessor_count ``` @@ -375,10 +420,14 @@ optional methods where it can do better than the fallback. In particular: ``` 4. Compute the typed index queries with `% T`, not `T(x)`: a checked conversion leaves an error branch in every kernel. -5. Sub-groups are optional. To support them, report [`supports_subgroups`](@ref) and - [`sub_group_size`](@ref), and implement the device functions the - [contract](@ref Contract) requires. If the backend has shuffles, implement them only for the - primitive types the hardware shuffles natively, including `UInt32`, and report those with +5. Sub-groups are optional. To support them, report [`supports_subgroups`](@ref) and the + widths a kernel can request with [`sub_group_sizes`](@ref), and implement the device + functions the [contract](@ref Contract) requires. `kernel_function` has to compile a + kernel with exactly the width given by its `sub_group_size` keyword, and throw an + `ArgumentError` for widths that aren't offered. Kernels compiled without the keyword may + run at any width, chosen per launch; `sub_group_size = nothing` means no request. A + backend that can't guarantee a width keeps the fallback `sub_group_sizes` of `()`. If the + backend has shuffles, implement them only for the primitive types the hardware shuffles natively, including `UInt32`, and report those with [`supports_shuffle`](@ref); KernelInterface shuffles other types as words. It also provides the reductions, scans and functions with a `width`; override those where a native implementation helps, keeping their documented results. diff --git a/docs/src/kernels.md b/docs/src/kernels.md index 6ead9aa21..42bccec30 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -272,6 +272,20 @@ kernel = my_kernel(backend, 32, size(A)) kernel(A) ``` +Any of these also takes a `sub_group_size` keyword, which compiles the kernel for that +sub-group width. It has to be one of the widths +[`KernelInterface.sub_group_sizes(backend)`](@ref KernelInterface.sub_group_sizes) offers, +and `nothing` (the default) requests none; other widths throw an `ArgumentError` when the +kernel is compiled. Without a request, the backend chooses the width, possibly per +launch. KernelAbstractions' collectives work at any width, so a width only needs +to be requested for performance, e.g. a narrower one on Intel GPUs for a kernel that uses +many registers, or by code that needs to know it on the host: + +```julia +sizes = KernelInterface.sub_group_sizes(backend) +kernel = my_kernel(backend, 256; sub_group_size = 16 in sizes ? 16 : nothing) +``` + ### Index ranges Each entry of `ndrange` is either an extent (indices `1:n`) or a range of indices, so a kernel diff --git a/lib/KernelInterface/Project.toml b/lib/KernelInterface/Project.toml index ae059408d..1d574a3e3 100644 --- a/lib/KernelInterface/Project.toml +++ b/lib/KernelInterface/Project.toml @@ -1,7 +1,7 @@ name = "KernelInterface" uuid = "4ee993da-d684-4d17-a7dd-4e58e78d92bf" authors = ["Valentin Churavy and contributors"] -version = "0.4.7" +version = "0.5.0" [compat] julia = "1.10" diff --git a/lib/KernelInterface/src/KernelInterface.jl b/lib/KernelInterface/src/KernelInterface.jl index fb19077ef..45b5a07ca 100644 --- a/lib/KernelInterface/src/KernelInterface.jl +++ b/lib/KernelInterface/src/KernelInterface.jl @@ -39,7 +39,7 @@ include("host.jl") # compilation and launch :Kernel, :kernel_function, :argconvert, :launch, Symbol("@launch"), :launch_configuration, :max_work_group_size, :max_work_group_dims, - :max_num_groups, :sub_group_size, :multiprocessor_count, + :max_num_groups, :sub_group_sizes, :multiprocessor_count, # host side :allocate, :zeros, :ones, :copyto!, :pagelock!, :unsafe_free!, :synchronize, :record_event, :wait_event, :priority!, diff --git a/lib/KernelInterface/src/device.jl b/lib/KernelInterface/src/device.jl index 321361000..e5f69159a 100644 --- a/lib/KernelInterface/src/device.jl +++ b/lib/KernelInterface/src/device.jl @@ -126,8 +126,12 @@ end ## sub-groups # Sub-group support is optional, see `supports_subgroups`. A work-group is divided into -# sub-groups of at most `sub_group_size(backend)` work-items. Which work-items form a -# sub-group, how many sub-groups there are and which are partial is unspecified (unless +# sub-groups of at most `get_max_sub_group_size()` work-items, the width of the kernel: the +# width `W` it was compiled for with `kernel_function(...; sub_group_size = W)`, or else one +# the backend chose for the launch. That one is the same for all work-items of a launch, but +# can differ between kernels and between launches of a kernel, and isn't known on the host. +# Which work-items form a sub-group, how +# many sub-groups there are and which are partial is unspecified (unless # `supports_linear_subgroups`), except that `(get_sub_group_id(), get_sub_group_local_id())` # is unique within a work-group and doesn't change during the kernel's execution (see the # manual). @@ -139,11 +143,10 @@ end """ get_sub_group_size([::Type{T}=Int])::T -The number of work-items in the sub-group, at most the sub-group width +The number of work-items in the sub-group, between 1 and the sub-group width ([`get_max_sub_group_size`](@ref)). Which sub-groups have fewer work-items than the width is unspecified (unless the layout is linear, see [`supports_linear_subgroups`](@ref)): there -can be more than one, -e.g. one per row of a multi-dimensional work-group. +can be more than one, e.g. one per row of a multi-dimensional work-group. See [`get_local_id`](@ref) for the supported types `T`. @@ -159,21 +162,24 @@ See [`get_local_id`](@ref) for the supported types `T`. """ get_max_sub_group_size([::Type{T}=Int])::T -The sub-group width (the warp or wavefront size), [`sub_group_size(backend)`](@ref -sub_group_size) on the host. +The sub-group width of the kernel (the warp or wavefront size), the same for all work-items +of a launch. It is only known on the host for kernels that requested a width; see +[`sub_group_sizes`](@ref). Backends should make it a constant of the generated code, so that code depending on it, e.g. a loop over the lanes or a shuffle butterfly, is specialized for it; on some, it is only folded late in compilation, or not at all. Don't rely on it being known during type inference: to pick types or `Val` parameters from the width, e.g. the integer type of a mask -with a bit per lane, pass [`sub_group_size(backend)`](@ref sub_group_size) from the host. +with a bit per lane, request a width `W` from [`sub_group_sizes`](@ref) when compiling the +kernel, and pass it from the host as well. See [`get_local_id`](@ref) for the supported types `T`. !!! note - Backend implementations that support sub-groups **must** implement this, and **should** - return the width the kernel is compiled for as a constant rather than query the device - at run time, so that code depending on it is specialized for the width: + Backend implementations that support sub-groups **must** implement this, returning the + requested width for kernels compiled with one. They **should** return the width the + kernel is compiled for as a constant rather than query the device at run time, so that + code depending on it is specialized for the width: ``` @device_override get_max_sub_group_size(::Type{T})::T where {T} ``` @@ -689,13 +695,15 @@ sub-group get the same result. `count_ones(mask)` counts the work-items, and for mask, `trailing_zeros(mask) + 1` is the lane of the first one. All work-items of the sub-group have to execute `sub_group_ballot` together (not in a -divergent branch); see [`shfl`](@ref). Only sub-groups of at most 64 work-items are supported. +divergent branch); see [`shfl`](@ref). Only sub-groups of at most 64 work-items are +supported: all widths in [`sub_group_sizes`](@ref) are, but a kernel compiled without a +requested width has to check [`get_max_sub_group_size`](@ref) to be sure. It doesn't synchronize memory accesses, see [`sub_group_barrier`](@ref). !!! note - Backend implementations that support sub-groups with a width of at most 64 **must** - implement: + Backend implementations that support sub-groups with a width of at most 64, which + includes all that offer a width in [`sub_group_sizes`](@ref), **must** implement: ``` @device_override sub_group_ballot(pred::Bool)::UInt64 ``` @@ -714,6 +722,7 @@ relative to the segment: bit `i - 1` for the `i`-th lane of the segment. Lanes w work-item don't count. For a `width` smaller than the sub-group width, they need a sub-group width of at most 64. +A kernel compiled without a requested width can check [`get_max_sub_group_size`](@ref). !!! note Backends **may** implement these. A backend that implements diff --git a/lib/KernelInterface/src/host.jl b/lib/KernelInterface/src/host.jl index c00a15d24..a4cbad29f 100644 --- a/lib/KernelInterface/src/host.jl +++ b/lib/KernelInterface/src/host.jl @@ -265,11 +265,13 @@ supports_float64(::Backend) = false """ supports_subgroups(::Backend)::Bool -Whether kernels on the active device support sub-groups with a fixed width -[`sub_group_size`](@ref): the sub-group queries ([`get_sub_group_size`](@ref) etc.), -[`sub_group_barrier`](@ref), and the votes [`sub_group_any`](@ref), [`sub_group_all`](@ref) -and, for widths of at most 64, [`sub_group_ballot`](@ref). Which types the shuffles support -is queried separately with [`supports_shuffle`](@ref). +Whether kernels on the active device support sub-groups: the sub-group queries +([`get_sub_group_size`](@ref) etc.), [`sub_group_barrier`](@ref), and the votes +[`sub_group_any`](@ref), [`sub_group_all`](@ref) and, for widths of at most 64, +[`sub_group_ballot`](@ref). Which types the shuffles support is queried separately with +[`supports_shuffle`](@ref). + +This doesn't imply a width that is known on the host: see [`sub_group_sizes`](@ref). Which work-items form a sub-group is unspecified, unless [`supports_linear_subgroups`](@ref) returns `true`, and the communication functions have to @@ -278,8 +280,13 @@ be executed in control flow that is uniform over the work-group, unless for the layout and participation guarantees. !!! note - Backend implementations **must** implement this function if they support sub-groups. - The fallback returns `false`. + Backend implementations **must** implement this function if they support sub-groups, + and [`sub_group_sizes`](@ref) if kernels can request a width. The fallback returns + `false`. + +!!! compat "KernelInterface 0.5" + Up to KernelInterface 0.4, sub-group support implied that every kernel had the same, + fixed width. """ supports_subgroups(::Backend) = false @@ -288,13 +295,17 @@ supports_subgroups(::Backend) = false Whether the active device forms sub-groups from consecutive work-items, for every kernel and launch with a 1-D work-group or one whose x extent is a multiple of the sub-group width `W` -([`sub_group_size`](@ref)): then the work-item with the linear local index `lin` (x -fastest, see [`get_local_id`](@ref)) is in sub-group `fld(lin - 1, W) + 1`, at lane -`mod(lin - 1, W) + 1`, the sub-group ids are `1:cld(n, W)` for a work-group of `n` +of the kernel, [`get_max_sub_group_size`](@ref): then the work-item with the linear local +index `lin` (x fastest, see [`get_local_id`](@ref)) is in sub-group `fld(lin - 1, W) + 1`, +at lane `mod(lin - 1, W) + 1`, the sub-group ids are `1:cld(n, W)` for a work-group of `n` work-items, and only the last sub-group can be partial. In particular, a 1-D work-group of at most `W` work-items is a single sub-group. It promises nothing about other work-group shapes. Implies [`supports_subgroups`](@ref). +The host knows `W`, and so which multi-dimensional work-groups this covers, only for kernels +compiled with a requested width (see [`sub_group_sizes`](@ref)). Other kernels can still rely +on the layout of 1-D work-groups, computing it from the width they read on the device. + Code needs this when it relates local ids to lanes: e.g. stencils that shuffle values between neighbouring work-items, transposes through shuffles, or work-group scans built from sub-group scans. Code that doesn't can index storage by the sub-group slot diff --git a/lib/KernelInterface/src/launch.jl b/lib/KernelInterface/src/launch.jl index 29e3c9735..58a08e848 100644 --- a/lib/KernelInterface/src/launch.jl +++ b/lib/KernelInterface/src/launch.jl @@ -339,24 +339,78 @@ dimension). The backend's validation at launch time is authoritative. function max_num_groups end """ - sub_group_size(backend)::Int + sub_group_sizes(backend)::Tuple{Vararg{Int}} -The sub-group width of kernels compiled for the active device of `backend`. +The sub-group widths that a kernel can request for the active device of `backend`, the one +the backend suggests first; the order of the others means nothing. -Kernels compiled by [`kernel_function`](@ref) execute with exactly this width: on the device, -[`get_max_sub_group_size`](@ref) returns it, and full sub-groups have this many work-items. -Host code can rely on it, e.g. to pick a `Val(N)` for a warp-level reduction. +A kernel compiled by [`kernel_function`](@ref) with `sub_group_size = W`, for a `W` in this +list, executes with exactly width `W`: on the device, [`get_max_sub_group_size`](@ref) +returns `W`, full sub-groups have `W` work-items, and the layout of +[`supports_linear_subgroups`](@ref) is relative to `W`. A kernel compiled without a request +(or with `sub_group_size = nothing`) runs at a width the backend chooses for each launch, +the same for all work-items of the launch, which they read with `get_max_sub_group_size`. + +Code that needs the width on the host, e.g. to pick a `Val(W)` for a warp-level reduction +or to size local memory, has to request one. If any width will do, take the first. +Hardware that supports several widths can be faster at a narrower one +for some kernels (e.g. because the kernel uses fewer registers per work-item) and at a wider +one for others, so code that knows its kernel's needs can pick another: + +```julia +sizes = KI.sub_group_sizes(backend) +if isempty(sizes) + # no width can be requested: use a kernel that doesn't need to know it on the host + KI.@launch backend workgroupsize=64 generic_reduce_kernel(out, a) +else + W = 16 in sizes ? 16 : first(sizes) + KI.@launch backend workgroupsize=4W sub_group_size=W reduce_kernel(out, a, Val(W)) +end +``` + +Only widths of at most 64 are offered, so that [`sub_group_ballot`](@ref) covers every lane. +The list is empty without sub-groups, but can also be empty when +[`supports_subgroups`](@ref) returns `true`: the device then has sub-groups, but can't +guarantee a width. Kernels then have to read the width on the +device, with [`get_max_sub_group_size`](@ref). !!! note - Backend implementations **must** implement this if [`supports_subgroups`](@ref) returns - `true`: + Backend implementations that let kernels request a width **must** implement this, and + the `sub_group_size` keyword of [`kernel_function`](@ref) for every width it returns: ``` - sub_group_size(backend::NewBackend)::Int + sub_group_sizes(backend::NewBackend)::Tuple{Vararg{Int}} ``` - A backend that cannot guarantee the width for every kernel has to report - `supports_subgroups(backend) = false`. + The fallback returns `()`: no width can be requested. + +!!! compat "KernelInterface 0.5" + This function, and the `sub_group_size` keyword of `kernel_function`, require at least + KernelInterface v0.5. Before, `sub_group_size(backend)` was the width of every kernel. """ -function sub_group_size end +sub_group_sizes(::Backend) = () + +""" + sub_group_size(backend) + +Removed in KernelInterface 0.5, and throws an error; the method itself will be removed in +KernelInterface 1.0. Kernels no longer have a width that is known on the host, unless they +request one. Pick a width from +[`sub_group_sizes(backend)`](@ref sub_group_sizes) and pass it to [`kernel_function`](@ref) +or [`@launch`](@ref KernelInterface.@launch) as `sub_group_size = W`, or read the width on +the device with [`get_max_sub_group_size`](@ref). + +!!! compat "KernelInterface 0.5" + Up to KernelInterface 0.4, this returned the sub-group width of every kernel compiled for + `backend`. +""" +function sub_group_size(::Backend) + error( + "`KI.sub_group_size(backend)` was removed in KernelInterface 0.5: kernels no longer " * + "have a fixed width unless they request one. Pick a width from " * + "`KI.sub_group_sizes(backend)` and pass it to `kernel_function`/`@launch` as " * + "`sub_group_size = W`, or read the width on the device with `get_max_sub_group_size()`. " * + "This method will be removed in KernelInterface 1.0." + ) +end """ multiprocessor_count(backend)::Int @@ -405,6 +459,9 @@ pointers to. Keyword arguments: - `name`: override the name that the kernel will have in the generated code. +- `sub_group_size`: the sub-group width to compile the kernel for, one of + [`sub_group_sizes(backend)`](@ref sub_group_sizes), which documents the guarantee. Other + widths throw an `ArgumentError`; `nothing`, like leaving the keyword out, requests none. Other keyword arguments are backend-specific compiler options (e.g. `maxthreads` for CUDA.jl); backends throw an error for options they don't support. @@ -424,8 +481,13 @@ launch. every launch, as it does for the arguments. The returned `Kernel` stores `backend` itself (not a new default backend), so that - options it carries apply to the launch. Kernels must execute with sub-group width - [`sub_group_size(backend)`](@ref sub_group_size) if the backend supports sub-groups. + options it carries apply to the launch. + + The `sub_group_size` keyword has to be accepted by every backend, with `nothing` meaning + no request. A width in [`sub_group_sizes(backend)`](@ref sub_group_sizes) has to give + the kernel exactly that width; any other width throws an `ArgumentError` (the backend + checks this itself, since callers reach its method directly). An offered width can still + fail to compile for a particular kernel, which then throws as well. Launching a kernel after [`device!`](@ref) switched to a device other than the one it was compiled for must either work, or throw an error: it may never run on the wrong @@ -457,7 +519,8 @@ Other keyword arguments: - `launch`: whether to launch the kernel, defaults to `true`. With `launch=false`, the kernel is only compiled and returned, and the launch keywords can't be used: launch it by calling it with the arguments and the launch keywords. -- `name` and any other keyword are passed to [`kernel_function`](@ref) as compiler options. +- `name`, `sub_group_size` and any other keyword are passed to [`kernel_function`](@ref) + as compiler options. Launch options specific to a backend (such as a CUDA stream) can't be passed to `@launch`; use `launch=false` and pass them when calling the kernel. diff --git a/lib/KernelInterface/test/interface.jl b/lib/KernelInterface/test/interface.jl index 6a200a69b..85b22d1ea 100644 --- a/lib/KernelInterface/test/interface.jl +++ b/lib/KernelInterface/test/interface.jl @@ -170,6 +170,34 @@ function test_subgroup_kernel(results) return end +# Checks the sub-groups of a work-group of shape `dims`, for a kernel of sub-group width +# `sg_size`. Which work-items form a sub-group, and how many sub-groups there are, is +# unspecified. +function check_subgroups(backend, data, dims, sg_size) + items = prod(dims) + @test all(d -> d.max_sub_group_size == sg_size, data) + # all work-items agree on the number of sub-groups, which is at least what full + # sub-groups would need + n = first(data).num_sub_groups + @test all(d -> d.num_sub_groups == n, data) + @test cld(items, sg_size) <= n <= items + # the sub-group ids are 1:n + @test sort(unique(map(d -> d.sub_group_id, data))) == 1:n + # every sub-group has as many members as its size says, and they are its lanes + for id in 1:n + members = filter(d -> d.sub_group_id == id, data) + size = length(members) + @test 1 <= size <= sg_size + @test all(d -> d.sub_group_size == size, members) + @test sort(map(d -> d.sub_group_local_id, members)) == 1:size + end + # with the linear layout, a 1-D work-group that fits a sub-group is one + if KI.supports_linear_subgroups(backend) && length(dims) == 1 && items <= sg_size + @test n == 1 + end + return +end + # Combine a value per sub-group through local memory, as reductions do: the first lane of # every sub-group stores its size, and the first work-item adds up `get_num_sub_groups()` # of them. `N` is the work-group size, which bounds the number of sub-groups. @@ -211,33 +239,40 @@ function subgroup_typecheck_kernel(results, val::T) where {T} return end -# the sub-group and lane of every work-item, by its linear index (x fastest) -function sub_group_layout_kernel(out) - l = KI.get_local_id() - sz = KI.get_local_size() - lin = l.x + (l.y - 1) * sz.x + (l.z - 1) * sz.x * sz.y - @inbounds begin - out[1, lin] = KI.get_sub_group_id() - out[2, lin] = KI.get_sub_group_local_id() - out[3, lin] = KI.get_sub_group_size() +# Compile `f(args...)` for `backend` with the sub-group width `W`, or without requesting a +# width if `W === nothing`. +function sub_group_kernel(backend, W, f, args...) + return if W === nothing + KI.@launch backend launch = false f(args...) + else + KI.@launch backend launch = false sub_group_size = W f(args...) end - return end -# The tests of the communication functions below don't assume which work-items form a -# sub-group (unless they are about `supports_linear_subgroups`): the kernels run in 1-D -# work-groups, every work-item records its sub-group, lane and sub-group size at its local -# index, and the expected results are computed on the host for the sub-groups that formed. +# The tests of the sub-group functions below don't assume which work-items form a sub-group +# (unless they are about `supports_linear_subgroups`), nor the width of kernels that don't +# request one: every work-item records its sub-group, lane, sub-group size and width at its +# local index, and the expected results are computed on the host for the sub-groups that +# formed, at the width the kernel reported. @inline function record_sub_group!(ids, i) @inbounds begin ids[1, i] = KI.get_sub_group_id() ids[2, i] = KI.get_sub_group_local_id() ids[3, i] = KI.get_sub_group_size() + ids[4, i] = KI.get_max_sub_group_size() end return end +# the sub-group ids of every work-item, by its linear index (x fastest) +function sub_group_layout_kernel(ids) + l = KI.get_local_id() + sz = KI.get_local_size() + record_sub_group!(ids, l.x + (l.y - 1) * sz.x + (l.z - 1) * sz.x * sz.y) + return +end + # every work-item applies `f`, which communicates within the sub-group, to its value of `a` function sub_group_apply_kernel(ids, out, a, f) i = KI.get_local_id().x @@ -246,8 +281,17 @@ function sub_group_apply_kernel(ids, out, a, f) return end +# the width all work-items of a launch reported, from the ids `record_sub_group!` wrote +function observed_width(ids) + W = ids[4, 1] + @test all(==(W), ids[4, :]) + return W +end + # the work-items of every sub-group by lane, from the ids `record_sub_group!` wrote function observed_sub_groups(ids) + W = observed_width(ids) + @test all(s -> 1 <= s <= W, ids[3, :]) groups = [Int[] for _ in 1:maximum(ids[1, :])] for i in axes(ids, 2) push!(groups[ids[1, i]], i) @@ -261,18 +305,21 @@ function observed_sub_groups(ids) end # Run `f` on the values `a` in a 1-D work-group of `length(a)` work-items, with results of -# type `T`. Returns the results by local index and the work-items of each sub-group, or +# type `T`, compiled for the sub-group width `W` (see `sub_group_kernel`). Returns the results +# by local index, the work-items of each sub-group and the width the kernel reported, or # `nothing` if the work-group is too large for the kernel. -function sub_group_apply(backend, AT, f, a, T = eltype(a)) +function sub_group_apply(backend, AT, W, f, a, T = eltype(a)) n = length(a) - ids = AT(zeros(Int, 3, n)) + ids = AT(zeros(Int, 4, n)) out = AT(Vector{T}(undef, n)) dev_a = AT(a) - kernel = KI.@launch backend launch = false sub_group_apply_kernel(ids, out, dev_a, f) + kernel = sub_group_kernel(backend, W, sub_group_apply_kernel, ids, out, dev_a, f) n <= KI.max_work_group_size(kernel) || return nothing kernel(ids, out, dev_a, f; workgroupsize = n) KI.synchronize(backend) - return Array(out), observed_sub_groups(Array(ids)) + ids = Array(ids) + W === nothing || @test observed_width(ids) == W + return Array(out), observed_sub_groups(ids), observed_width(ids) end # work-group sizes that form full and partial sub-groups, several of them, and a single @@ -331,10 +378,10 @@ end shuffle_source(r::Rotate, l, size, W) = mod1(l + r.shift, size) shuffle_source(s::AsType, l, size, W) = shuffle_source(s.f, l, size, W) -function shuffle_testsuite(backend, AT, sg_size, f, a) - res = sub_group_apply(backend, AT, f, a) +function shuffle_testsuite(backend, AT, W, f, a) + res = sub_group_apply(backend, AT, W, f, a) res === nothing && return - out, groups = res + out, groups, sg_size = res ok = true for g in groups, (l, i) in enumerate(g) src = shuffle_source(f, l, length(g), sg_size) @@ -455,10 +502,10 @@ end collective_op(f) = f.op reassociable(f, ::Type{T}) where {T} = T <: AbstractFloat && collective_op(f) in (+, *) -function collective_testsuite(backend, AT, f, a) - res = sub_group_apply(backend, AT, f, a) +function collective_testsuite(backend, AT, W, f, a) + res = sub_group_apply(backend, AT, W, f, a) res === nothing && return - out, groups = res + out, groups, _ = res T = eltype(a) ok = true for g in groups @@ -477,17 +524,21 @@ function collective_testsuite(backend, AT, f, a) return end -function vote_testsuite(backend, AT, sg_size, pred) - for (vote, T) in ((KI.sub_group_any, Bool), (KI.sub_group_all, Bool), (KI.sub_group_ballot, UInt64)) - vote === KI.sub_group_ballot && sg_size > 64 && continue - res = sub_group_apply(backend, AT, vote, pred, T) +# `sub_group_ballot` for kernels without a requested width, which may be wider than 64 +narrow_ballot(p) = KI.get_max_sub_group_size() <= 64 ? KI.sub_group_ballot(p) : typemax(UInt64) + +function vote_testsuite(backend, AT, W, pred) + ballot = W === nothing ? narrow_ballot : KI.sub_group_ballot + for (vote, T) in ((KI.sub_group_any, Bool), (KI.sub_group_all, Bool), (ballot, UInt64)) + res = sub_group_apply(backend, AT, W, vote, pred, T) res === nothing && continue - out, groups = res + out, groups, sg_size = res ok = true for g in groups p = pred[g] expected = vote === KI.sub_group_any ? any(p) : vote === KI.sub_group_all ? all(p) : + sg_size > 64 ? typemax(UInt64) : reduce(|, (UInt64(1) << (l - 1) for l in eachindex(p) if p[l]); init = UInt64(0)) ok &= all(i -> out[i] == expected, g) end @@ -505,11 +556,9 @@ end function width_vote_testsuite(backend, AT, sg_size, pred) for w in segment_widths(sg_size), (vote, T) in ((KI.sub_group_any, Bool), (KI.sub_group_all, Bool), (KI.sub_group_ballot, UInt64)) - # the votes within segments narrower than the sub-group use its ballot - (vote === KI.sub_group_ballot || w < sg_size) && sg_size > 64 && continue - res = sub_group_apply(backend, AT, WidthVote(vote, w), pred, T) + res = sub_group_apply(backend, AT, sg_size, WidthVote(vote, w), pred, T) res === nothing && continue - out, groups = res + out, groups, _ = res ok = true for g in groups, (l, i) in enumerate(g) ok &= out[i] == vote_result(vote, pred[g[segment_lanes(l, w, length(g))]]) @@ -531,14 +580,15 @@ function reduce_divergent_kernel(ids, red, scan, a, m) return end -function reduce_divergent_testsuite(backend, AT, sg_size, ::Type{T}) where {T} - n = sg_size - m = max(n - 5, 1) +# `n` work-items, of which the first `m` have a value, in a kernel of sub-group width `W` +function reduce_divergent_testsuite(backend, AT, W, ::Type{T}, n, m = max(n - 5, 1)) where {T} a = T.(rand(1:20, n)) - ids = AT(zeros(Int, 3, n)) + ids = AT(zeros(Int, 4, n)) red = AT(zeros(T, n)) scan = AT(zeros(T, n)) - KI.@launch backend workgroupsize = n reduce_divergent_kernel(ids, red, scan, AT(a), m) + kernel = sub_group_kernel(backend, W, reduce_divergent_kernel, ids, red, scan, AT(a), m) + n <= KI.max_work_group_size(kernel) || return + kernel(ids, red, scan, AT(a), m; workgroupsize = n) KI.synchronize(backend) red, scan = Array(red), Array(scan) vals = [i <= m ? a[i] : zero(T) for i in 1:n] @@ -574,8 +624,8 @@ end function independent_sub_groups_testsuite(backend, AT, sg_size) n = 4 * sg_size a = Int32.(rand(1:2000, n)) - ids, out = AT(zeros(Int, 3, n)), AT(zeros(Int32, n)) - kernel = KI.@launch backend launch = false independent_sub_groups_kernel(ids, out, AT(a)) + ids, out = AT(zeros(Int, 4, n)), AT(zeros(Int32, n)) + kernel = sub_group_kernel(backend, sg_size, independent_sub_groups_kernel, ids, out, AT(a)) n = min(n, KI.max_work_group_size(kernel)) kernel(ids, out, AT(a); workgroupsize = n) KI.synchronize(backend) @@ -692,8 +742,8 @@ function partitioned_subgroups_testsuite(backend, AT, sg_size) w < sg_size || continue n = 4 * sg_size a = Int32[rand(Bool) ? rand(501:2000) : rand(1:2000) for _ in 1:n] - ids, out = AT(zeros(Int, 3, n)), AT(zeros(Int32, 6, n)) - kernel = KI.@launch backend launch = false partitioned_subgroups_kernel(ids, out, AT(a), w, Val(n)) + ids, out = AT(zeros(Int, 4, n)), AT(zeros(Int32, 6, n)) + kernel = sub_group_kernel(backend, sg_size, partitioned_subgroups_kernel, ids, out, AT(a), w, Val(n)) m = min(n, fld(KI.max_work_group_size(kernel), sg_size) * sg_size) kernel(ids, out, AT(a), w, Val(n); workgroupsize = m) KI.synchronize(backend) @@ -716,7 +766,7 @@ function partitioned_subgroups_testsuite(backend, AT, sg_size) groups = 64 errors, scratch = AT(fill(Int32(-1), n * groups)), AT(zeros(Int32, n * groups)) - kernel = KI.@launch backend launch = false segment_exchange_kernel(errors, scratch, w, Val(n)) + kernel = sub_group_kernel(backend, sg_size, segment_exchange_kernel, errors, scratch, w, Val(n)) m = min(n, fld(KI.max_work_group_size(kernel), sg_size) * sg_size) for _ in 1:10 kernel(errors, scratch, w, Val(n); workgroupsize = m, numgroups = groups) @@ -755,47 +805,253 @@ function captured_array_kernel(backend, AT, out) return kernel, WeakRef(a) end +# Checks that the sub-groups of a work-group of shape `dims` are formed from consecutive +# work-items, x fastest, at the width the kernel reported. +function check_linear_layout(ids, dims) + n = prod(dims) + W = observed_width(ids) + @test ids[1, :] == [(lin - 1) ÷ W + 1 for lin in 1:n] + @test ids[2, :] == [(lin - 1) % W + 1 for lin in 1:n] + @test ids[3, :] == [min(W, n - (lin - 1) ÷ W * W) for lin in 1:n] + return +end + # 1-D work-groups and ones whose x extent is a multiple of the sub-group width form -# sub-groups from consecutive work-items, x fastest -function sub_group_layout_testsuite(backend, AT, sg_size, fits) +# sub-groups from consecutive work-items, x fastest. `W` is the requested width; without +# one, only 1-D work-groups are checked, as the host doesn't know the width. +function sub_group_layout_testsuite(backend, AT, W, fits) # including one with a partial last sub-group past 256 work-items, which catches 8-bit # arithmetic in the index computations - shapes = ( - (sg_size + 5,), (3 * sg_size,), (9 * sg_size + 5,), - (sg_size, 4), (2 * sg_size, 2), (sg_size, 2, 2), - ) + shapes = if W === nothing + ((5,), (33,), (64,), (100,), (300,)) + else + ((W + 5,), (3 * W,), (9 * W + 5,), (W, 4), (2 * W, 2), (W, 2, 2)) + end for dims in shapes - n = prod(dims) - out = AT(zeros(Int, 3, n)) - kernel = KI.@launch backend launch = false sub_group_layout_kernel(out) + ids = AT(zeros(Int, 4, prod(dims))) + kernel = sub_group_kernel(backend, W, sub_group_layout_kernel, ids) if !fits(kernel, dims) @test_skip "work-groups of $dims work-items" continue end - kernel(out; workgroupsize = dims) + kernel(ids; workgroupsize = dims) KI.synchronize(backend) - out = Array(out) + ids = Array(ids) @testset "$dims" begin - @test out[1, :] == [(lin - 1) ÷ sg_size + 1 for lin in 1:n] - @test out[2, :] == [(lin - 1) % sg_size + 1 for lin in 1:n] - @test out[3, :] == [min(sg_size, n - (lin - 1) ÷ sg_size * sg_size) for lin in 1:n] + W === nothing || @test observed_width(ids) == W + check_linear_layout(ids, dims) end end return end -# The sub-group communication functions. A separate function, so that `interface_testsuite` -# doesn't get too large to compile. -function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size) +# work-group shapes to check for a kernel of sub-group width `W`: 1-D ones around the width, +# and multi-dimensional ones whose first dimension is or isn't a multiple of the width +function subgroup_shapes(W) + shapes = unique( + [ + (W - 1,), (W,), (W + 1,), (2 * W,), (2 * W + 1,), + (33, 2), (W, 2), (W + 1, 2), (7, 5), (5, 3, 2), (W, 2, 2), + ] + ) + return filter(dims -> all(>(0), dims), shapes) +end + +# the same, for kernels whose width the host doesn't know +const unrequested_subgroup_shapes = [ + (1,), (7,), (16,), (32,), (33,), (64,), (65,), (100,), (257,), + (33, 2), (16, 4), (7, 5), (5, 3, 2), +] + +# Launches `test_subgroup_kernel` with work-groups of shape `dims`, compiled for the +# sub-group width `W` (see `sub_group_kernel`; with `explicit`, `W` is passed as the keyword +# even if it is `nothing`), and returns the data of every work-group, or +# `nothing` if the kernel can't be launched with that shape. +function subgroup_data(backend, AT, W, dims, fits; numgroups = 2, explicit = false) + items = prod(dims) + results = AT(Vector{SubgroupData}(undef, items * numgroups)) + kernel = if explicit + KI.@launch backend launch = false sub_group_size = W test_subgroup_kernel(results) + else + sub_group_kernel(backend, W, test_subgroup_kernel, results) + end + fits(kernel, dims) || return nothing + kernel(results; workgroupsize = dims, numgroups) + KI.synchronize(backend) + return [collect(group) for group in Iterators.partition(Array(results), items)] +end + +function subgroup_typecheck_testsuite(backend, AT, W, fits) + types = filter(T -> KI.supports_shuffle(backend, T), [Int32, Float32, Int64, UInt32]) + isempty(types) && return + results = KI.zeros(backend, Bool, 11) + val = one(first(types)) + kernel = sub_group_kernel(backend, W, subgroup_typecheck_kernel, results, val) + n = something(W, 32) + if fits(kernel, (n,)) + kernel(results, val; workgroupsize = n) + KI.synchronize(backend) + @test all(Array(results)) + else + @test_skip "work-groups of $n work-items" + end + return +end + +# The sub-group queries and layout of kernels compiled with the sub-group width `W`. +function requested_subgroup_testsuite(backend, AT, W, fits) + @testset "Sub-group layout" begin + if KI.supports_linear_subgroups(backend) + sub_group_layout_testsuite(backend, AT, W, fits) + end + end + + @testset "Sub-group return types" begin + subgroup_typecheck_testsuite(backend, AT, W, fits) + end + + @testset "Sub-group formation" begin + @testset "$dims" for dims in subgroup_shapes(W) + groups = subgroup_data(backend, AT, W, dims, fits) + if groups === nothing + @test_skip "work-groups of $dims work-items" + continue + end + for data in groups + check_subgroups(backend, data, dims, W) + # the requested width is used, not just bounded: with the linear layout, + # which covers these shapes, rows of at least `W` work-items form a full + # sub-group + KI.supports_linear_subgroups(backend) && dims[1] >= W && + (length(dims) == 1 || dims[1] % W == 0) && + @test any(d -> d.sub_group_size == W, data) + end + end + end + + # a collective over a full and a partial sub-group, at widths whose communication + # functions aren't all tested + if KI.supports_shuffle(backend, UInt32) + @testset "sub_group_reduce" begin + a = Int32.(rand(1:100, W + 1)) + res = sub_group_apply(backend, AT, W, Reduce(+), a) + if res === nothing + @test_skip "work-groups of $(W + 1) work-items" + else + out, groups, _ = res + KI.supports_linear_subgroups(backend) && @test maximum(length, groups) == W + @test all(g -> out[g] == fill(sum(a[g]), length(g)), groups) + end + end + end + return +end + +# `shfl_xor` with the largest mask the width allows, computed on the device +struct XorTop end +function (::XorTop)(x) + W = KI.get_max_sub_group_size() + return KI.shfl_xor(x, ispow2(W) ? W - 1 : 0) +end +shuffle_source(::XorTop, l, size, W) = in_sub_group(((l - 1) ⊻ (ispow2(W) ? W - 1 : 0)) + 1, size) + +# Kernels compiled without a requested width run at a width the backend chooses for each +# launch, which the host doesn't know: these check the sub-groups, and some of the +# communication functions, against the width each launch reports. +function unrequested_subgroup_testsuite(backend, AT, fits) + @testset "Sub-group formation$(explicit ? ", with sub_group_size = nothing" : "")" for explicit in (false, true) + @testset "$dims" for dims in unrequested_subgroup_shapes + groups = subgroup_data(backend, AT, nothing, dims, fits; explicit) + if groups === nothing + @test_skip "work-groups of $dims work-items" + continue + end + # all work-items of the launch agree on the width + W = first(first(groups)).max_sub_group_size + @test W >= 1 + @test all(data -> all(d -> d.max_sub_group_size == W, data), groups) + for data in groups + check_subgroups(backend, data, dims, W) + end + end + end + + @testset "Sub-group layout" begin + if KI.supports_linear_subgroups(backend) + sub_group_layout_testsuite(backend, AT, nothing, fits) + end + end + + @testset "Sub-group return types" begin + subgroup_typecheck_testsuite(backend, AT, nothing, fits) + end + + @testset "Combining a value per sub-group" begin + numgroups = 3 + @testset "$dims" for dims in unrequested_subgroup_shapes + out = KI.zeros(backend, Int32, numgroups) + kernel = KI.@launch backend launch = false subgroup_combine_kernel(out, Val(prod(dims))) + if fits(kernel, dims) + kernel(out, Val(prod(dims)); workgroupsize = dims, numgroups) + KI.synchronize(backend) + @test all(==(prod(dims)), Array(out)) + else + @test_skip "work-groups of $dims work-items" + end + end + end + + sizes = (1, 7, 33, 100) + @testset "votes" begin + @testset "$n work-items" for n in sizes + for pred in (falses(n), trues(n), [i % 3 == 1 for i in 1:n], rand(Bool, n)) + vote_testsuite(backend, AT, nothing, collect(pred)) + end + end + end + + KI.supports_shuffle(backend, UInt32) || return + + @testset "shuffles" begin + @testset "$n work-items" for n in sizes + a = Int32.(1:n) .* Int32(10) + for f in Any[Rotate(1), Shuffle(KI.shfl, 1), Shuffle(KI.shfl_down, 1), Shuffle(KI.shfl_up, 1), XorTop()] + shuffle_testsuite(backend, AT, nothing, f, a) + end + end + end + + @testset "sub_group_reduce and scans" begin + @testset "$n work-items" for n in sizes + affine = [(Int32(rand((-1, 1, 2))), Int32(rand(-5:5))) for _ in 1:n] + for (op, a) in Any[(+, Int32.(rand(1:100, n))), (max, Float32.(rand(1:100, n))), (compose_affine, affine)] + KI.supports_shuffle(backend, eltype(a)) || continue + collective_testsuite(backend, AT, nothing, Reduce(op), a) + collective_testsuite(backend, AT, nothing, Scan(op), a) + end + collective_testsuite(backend, AT, nothing, ExclusiveScan(+, Int32(7)), Int32.(rand(1:100, n))) + end + @testset "of divergent values, $n work-items" for n in (33, 100) + reduce_divergent_testsuite(backend, AT, nothing, Int32, n) + end + end + return +end + +# The sub-group communication functions, for kernels compiled with the sub-group width +# `sg_size`. A separate function, so that `interface_testsuite` doesn't get too large to +# compile. +function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size::Int) sizes = sub_group_test_sizes(sg_size) fp64 = KI.supports_float64(backend) @testset "sub_group_barrier" begin n = sg_size - ids = AT(zeros(Int, 3, n)) + ids = AT(zeros(Int, 4, n)) scratch = AT(zeros(Int32, n * sg_size)) out = AT(zeros(Int32, n, 2)) - KI.@launch backend workgroupsize = n sub_group_barrier_kernel(ids, scratch, out, Val(n * sg_size)) + kernel = sub_group_kernel(backend, sg_size, sub_group_barrier_kernel, ids, scratch, out, Val(n * sg_size)) + kernel(ids, scratch, out, Val(n * sg_size); workgroupsize = n) KI.synchronize(backend) out = Array(out) for g in observed_sub_groups(Array(ids)), (l, i) in enumerate(g) @@ -804,10 +1060,11 @@ function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size) end @testset "with a width of $w" for w in segment_widths(sg_size) - ids = AT(zeros(Int, 3, n)) + ids = AT(zeros(Int, 4, n)) scratch = AT(zeros(Int32, n * sg_size)) out = AT(zeros(Int32, n, 2)) - KI.@launch backend workgroupsize = n segment_barrier_kernel(ids, scratch, out, w, Val(n * sg_size)) + kernel = sub_group_kernel(backend, sg_size, segment_barrier_kernel, ids, scratch, out, w, Val(n * sg_size)) + kernel(ids, scratch, out, w, Val(n * sg_size); workgroupsize = n) KI.synchronize(backend) out = Array(out) for g in observed_sub_groups(Array(ids)), (l, i) in enumerate(g) @@ -920,22 +1177,22 @@ function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size) end for (op, a) in ops KI.supports_shuffle(backend, eltype(a)) || continue - collective_testsuite(backend, AT, Reduce(op), a) - collective_testsuite(backend, AT, Scan(op), a) + collective_testsuite(backend, AT, sg_size, Reduce(op), a) + collective_testsuite(backend, AT, sg_size, Scan(op), a) end # exclusive scans with an `init` that isn't the identity - collective_testsuite(backend, AT, ExclusiveScan(+, Int32(7)), Int32.(rand(1:100, n))) - collective_testsuite(backend, AT, ExclusiveScan(+, UInt64(7)), UInt64.(rand(1:100, n))) - collective_testsuite(backend, AT, ExclusiveScan(max, Int32(50)), Int32.(rand(1:100, n))) - collective_testsuite(backend, AT, ExclusiveScan(+, 7.0f0), Float32.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(+, Int32(7)), Int32.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(+, UInt64(7)), UInt64.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(max, Int32(50)), Int32.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(+, 7.0f0), Float32.(rand(1:100, n))) collective_testsuite( - backend, AT, ExclusiveScan(compose_affine, (Int32(2), Int32(3))), + backend, AT, sg_size, ExclusiveScan(compose_affine, (Int32(2), Int32(3))), [(Int32(rand((-1, 1, 2))), Int32(rand(-5:5))) for _ in 1:n] ) # lane 1 gets `init` itself, not `init + 0.0` - collective_testsuite(backend, AT, ExclusiveScan(+, -0.0f0), Float32.(rand(1:100, n))) - collective_testsuite(backend, AT, ExclusiveScan(+, -0.0f0), fill(-0.0f0, n)) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(+, -0.0f0), Float32.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, ExclusiveScan(+, -0.0f0), fill(-0.0f0, n)) end @testset "with a width, $n work-items" for n in sizes @@ -946,12 +1203,12 @@ function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size) (compose_affine, [(Int32(rand((-1, 1, 2))), Int32(rand(-5:5))) for _ in 1:n]), ] for (op, a) in ops - collective_testsuite(backend, AT, WidthReduce(op, w), a) - collective_testsuite(backend, AT, WidthScan(op, w), a) + collective_testsuite(backend, AT, sg_size, WidthReduce(op, w), a) + collective_testsuite(backend, AT, sg_size, WidthScan(op, w), a) end - collective_testsuite(backend, AT, WidthExclusiveScan(+, Int32(7), w), Int32.(rand(1:100, n))) + collective_testsuite(backend, AT, sg_size, WidthExclusiveScan(+, Int32(7), w), Int32.(rand(1:100, n))) collective_testsuite( - backend, AT, WidthExclusiveScan(compose_affine, (Int32(2), Int32(3)), w), + backend, AT, sg_size, WidthExclusiveScan(compose_affine, (Int32(2), Int32(3)), w), [(Int32(rand((-1, 1, 2))), Int32(rand(-5:5))) for _ in 1:n] ) end @@ -959,8 +1216,8 @@ function subgroup_communication_testsuite(backend::KI.Backend, AT, sg_size) end @testset "sub_group_reduce and sub_group_scan of divergent values" begin - reduce_divergent_testsuite(backend, AT, sg_size, Int32) - reduce_divergent_testsuite(backend, AT, sg_size, Float32) + reduce_divergent_testsuite(backend, AT, sg_size, Int32, sg_size) + reduce_divergent_testsuite(backend, AT, sg_size, Float32, sg_size) end if KI.supports_independent_subgroups(backend) @@ -992,6 +1249,13 @@ function interface_testsuite(backend::KI.Backend, AT) @test all(==(1), run((6, 10, 1); numgroups = (2, 5), workgroupsize = (3, 2))) @test all(==(1), run((6, 10, 12); numgroups = (2, 5, 3), workgroupsize = (3, 2, 4))) + # every backend accepts `sub_group_size = nothing`, as no request + arr = KI.zeros(backend, Int32, (6, 1, 1)) + kernel = KI.@launch backend launch = false sub_group_size = nothing launch_kernel(arr) + kernel(arr; numgroups = 3, workgroupsize = 2) + KI.synchronize(backend) + @test all(==(1), Array(arr)) + # `ndrange` rounds up to whole groups, and doesn't mask the padding @test all(==(1), run((7, 5, 3); ndrange = (7, 5, 3), workgroupsize = (2, 3, 2))) @test all(==(1), run((7, 5, 3); ndrange = (7, 5, 3))) @@ -1326,106 +1590,39 @@ function interface_testsuite(backend::KI.Backend, AT) end if KI.supports_subgroups(backend) - sg_size = KI.sub_group_size(backend) max_dims = KI.max_work_group_dims(backend) # whether `kernel` can be launched with work-groups of size `dims` fits(kernel, dims) = all(dims .<= max_dims[1:length(dims)]) && prod(dims) <= KI.max_work_group_size(kernel) - @testset "Sub-group layout" begin - if KI.supports_linear_subgroups(backend) - sub_group_layout_testsuite(backend, AT, sg_size, fits) - end + @testset "Sub-groups without a requested width" begin + unrequested_subgroup_testsuite(backend, AT, fits) end - @testset "Sub-group return types" begin - @test sg_size isa Int && sg_size >= 1 - - types = filter(T -> KI.supports_shuffle(backend, T), [Int32, Float32, Int64, UInt32]) - if !isempty(types) - results = KI.zeros(backend, Bool, 11) - val = one(first(types)) - kernel = KI.@launch backend launch = false subgroup_typecheck_kernel(results, val) - if fits(kernel, (sg_size,)) - kernel(results, val; workgroupsize = sg_size) - KI.synchronize(backend) - @test all(Array(results)) - else - @test_skip "work-groups of $sg_size work-items" - end + sizes = KI.sub_group_sizes(backend) + @test sizes isa Tuple{Vararg{Int}} + @test allunique(sizes) && all(W -> 1 <= W <= 64, sizes) + # The communication functions take most of the time, so they are only tested for the + # first width, which most kernels use, and for the narrowest and the widest. + communication_widths = isempty(sizes) ? () : unique((first(sizes), minimum(sizes), maximum(sizes))) + @testset "Sub-group width $W" for W in sizes + requested_subgroup_testsuite(backend, AT, W, fits) + if W in communication_widths + subgroup_communication_testsuite(backend, AT, W) end end - # checks the sub-groups of a work-group of shape `dims`. Which work-items form a - # sub-group, and how many sub-groups there are, is unspecified. - function check_subgroups(data, dims) - items = prod(dims) - @test all(d -> d.max_sub_group_size == sg_size, data) - # all work-items agree on the number of sub-groups, which is at least what full - # sub-groups would need - n = first(data).num_sub_groups - @test all(d -> d.num_sub_groups == n, data) - @test cld(items, sg_size) <= n <= items - # the sub-group ids are 1:n - @test sort(unique(map(d -> d.sub_group_id, data))) == 1:n - # every sub-group has as many members as its size says, and they are its lanes - for id in 1:n - members = filter(d -> d.sub_group_id == id, data) - size = length(members) - @test 1 <= size <= sg_size - @test all(d -> d.sub_group_size == size, members) - @test sort(map(d -> d.sub_group_local_id, members)) == 1:size - end - # with the linear layout, a 1-D work-group that fits a sub-group is one - if KI.supports_linear_subgroups(backend) && length(dims) == 1 && items <= sg_size - @test n == 1 - end - return - end - - # work-group shapes to check: 1-D ones around the width, and multi-dimensional ones - # whose first dimension is or isn't a multiple of the width - subgroup_shapes = unique( - [ - (sg_size - 1,), (sg_size,), (sg_size + 1,), (2 * sg_size,), (2 * sg_size + 1,), - (33, 2), (sg_size, 2), (sg_size + 1, 2), (7, 5), (5, 3, 2), (sg_size, 2, 2), - ] - ) - filter!(dims -> all(>(0), dims), subgroup_shapes) - - @testset "Sub-group formation" begin - numgroups = 2 - @testset "$dims" for dims in subgroup_shapes - items = prod(dims) - results = AT(Vector{SubgroupData}(undef, items * numgroups)) - kernel = KI.@launch backend launch = false test_subgroup_kernel(results) - if fits(kernel, dims) - kernel(results; workgroupsize = dims, numgroups) - KI.synchronize(backend) - for group in Iterators.partition(Array(results), items) - check_subgroups(collect(group), dims) - end - else - @test_skip "work-groups of $dims work-items" - end - end - end + else + @test KI.sub_group_sizes(backend) == () + end - @testset "Combining a value per sub-group" begin - numgroups = 3 - @testset "$dims" for dims in subgroup_shapes - out = KI.zeros(backend, Int32, numgroups) - kernel = KI.@launch backend launch = false subgroup_combine_kernel(out, Val(prod(dims))) - if fits(kernel, dims) - kernel(out, Val(prod(dims)); workgroupsize = dims, numgroups) - KI.synchronize(backend) - @test all(==(prod(dims)), Array(out)) - else - @test_skip "work-groups of $dims work-items" - end - end + # widths the backend doesn't offer, including any if it offers none + @testset "Rejected sub-group widths" begin + sizes = KI.sub_group_sizes(backend) + tt = KI.argument_types(backend, (AT(zeros(Int, 4)),)) + for W in (2 * maximum(sizes; init = 32), 3) + W in sizes && continue + @test_throws ArgumentError KI.kernel_function(backend, launch_kernel, tt; sub_group_size = W) end - - subgroup_communication_testsuite(backend, AT, sg_size) end return nothing end @@ -1442,10 +1639,7 @@ function contract_testsuite(backend::KI.Backend, AT) @test hasmethod(KI.max_work_group_size, Tuple{KI.Kernel{B}}) @test hasmethod(KI.max_work_group_dims, Tuple{B}) @test hasmethod(KI.max_num_groups, Tuple{B}) - if KI.supports_subgroups(backend) - @test hasmethod(KI.sub_group_size, Tuple{B}) - # the device functions are overlays, so they can't be checked here; the sub-group - # testsuite runs them - end + # removed in KernelInterface 0.5; a backend that still implements it hides the error + @test_throws ErrorException KI.sub_group_size(backend) return end diff --git a/lib/KernelInterface/test/runtests.jl b/lib/KernelInterface/test/runtests.jl index 984f6628d..675462b07 100644 --- a/lib/KernelInterface/test/runtests.jl +++ b/lib/KernelInterface/test/runtests.jl @@ -36,7 +36,7 @@ KI.supports_shuffle(::WordShuffleBackend, ::Type{UInt32}) = true # them should get a MethodError rather than silently wrong behaviour. stubs = [ KI.max_work_group_size, KI.max_work_group_dims, KI.max_num_groups, - KI.sub_group_size, KI.argconvert, KI.kernel_function, KI.launch, + KI.argconvert, KI.kernel_function, KI.launch, # Host-side stubs: required backend methods with no sensible fallback. KI.synchronize, KI.copyto!, ] @@ -113,6 +113,10 @@ end struct StubBackend <: KI.Backend end +# A backend with sub-groups, but no width that kernels can request. +struct SubgroupBackend <: KI.Backend end +KI.supports_subgroups(::SubgroupBackend) = true + # A backend with two devices that forgot the other device functions. struct MultiDeviceBackend <: KI.Backend end KI.ndevices(::MultiDeviceBackend) = 2 @@ -143,6 +147,12 @@ end @test KI.multiprocessor_count(StubBackend()) == 0 @test KI.supports_subgroups(StubBackend()) === false @test KI.supports_shuffle(StubBackend(), Float32) === false + # no width can be requested unless the backend says which + @test KI.sub_group_sizes(StubBackend()) === () + @test KI.sub_group_sizes(SubgroupBackend()) === () + # the host-side width is gone, and says so + @test_throws "was removed in KernelInterface 0.5" KI.sub_group_size(StubBackend()) + @test_throws "was removed in KernelInterface 0.5" KI.sub_group_size(SubgroupBackend()) # `localmemory` forwards the untyped `dims` to the `Val` form backends override. # Off-device that form is unimplemented, and must error rather than recurse @@ -514,6 +524,10 @@ end named = KI.@launch backend launch = false name = "mykernel" maxthreads = 32 dummy(1, 2.0) @test named.kern.name == "mykernel" @test named.kern.options == Dict(:maxthreads => 32) + # including a requested sub-group width + W = 16 + requested = KI.@launch backend launch = false sub_group_size = W dummy(1, 2.0) + @test requested.kern.options == Dict(:sub_group_size => 16) optioned = KI.@launch backend ndrange = 4 maxthreads = 32 dummy(1, 2.0) @test isempty(only(optioned.kern.launches).kwargs) diff --git a/src/KernelAbstractions.jl b/src/KernelAbstractions.jl index bda2510d3..a40f3ca55 100644 --- a/src/KernelAbstractions.jl +++ b/src/KernelAbstractions.jl @@ -525,9 +525,11 @@ import .NDIteration: get ### """ - Kernel{Backend, WorkgroupSize, NDRange, Func} + Kernel{Backend, WorkgroupSize, NDRange, Func, Options} -Host-side handle for a kernel specialized on a backend, workgroup size, and `ndrange`. +Host-side handle for a kernel specialized on a backend, workgroup size, and `ndrange`. It +also holds the compiler options the kernel was constructed with, such as the sub-group width +it requested (`my_kernel(backend; sub_group_size = W)`). Kernels are created by calling a [`@kernel`](@ref) function on a backend, for example `my_kernel(CUDABackend(), 256)`. The returned object is callable: @@ -544,13 +546,18 @@ and [`backend`](@ref KernelAbstractions.backend) to inspect a kernel's static co Kernels are launched on any backend that implements [KernelInterface](@ref kernelinterface); see the [notes for backend implementations](@ref implementations_notes). """ -struct Kernel{Backend, WorkgroupSize <: _Size, NDRange <: _Size, Fun} +struct Kernel{Backend, WorkgroupSize <: _Size, NDRange <: _Size, Fun, Options <: NamedTuple} backend::Backend f::Fun + # compiler options passed to `KI.kernel_function`. their names are part of the type, so + # that a kernel without a request doesn't compile the path for one. + options::Options end +Kernel{B, WS, ND, F}(backend, f, options::O = (;)) where {B, WS, ND, F, O} = + Kernel{B, WS, ND, F, O}(backend, f, options) function Base.similar(kernel::Kernel{D, WS, ND}, f::F) where {D, WS, ND, F} - return Kernel{D, WS, ND, F}(kernel.backend, f) + return Kernel{D, WS, ND, F}(kernel.backend, f, kernel.options) end """ @@ -654,8 +661,12 @@ last (possibly partial) workgroup. Primarily used by backend implementations and return iterspace, dynamic end -function construct(backend::B, ::S, ::NDRange, xpu_name::XPUName) where {B <: Backend, S <: _Size, NDRange <: _Size, XPUName} - return Kernel{B, S, NDRange, XPUName}(backend, xpu_name) +function construct( + backend::B, ::S, ::NDRange, xpu_name::XPUName; sub_group_size = nothing + ) where {B <: Backend, S <: _Size, NDRange <: _Size, XPUName} + # passed on unconverted, so that the backend rejects widths it doesn't offer + options = sub_group_size === nothing ? (;) : (; sub_group_size) + return Kernel{B, S, NDRange, XPUName}(backend, xpu_name, options) end ### diff --git a/src/backend_launch.jl b/src/backend_launch.jl index 07efbd8b6..939023fdf 100644 --- a/src/backend_launch.jl +++ b/src/backend_launch.jl @@ -73,6 +73,12 @@ their backend type; the default is no options. """ compiler_options(::Kernel) = (;) +# `compile(args...)` with the options `kernel` is compiled with: the backend's, and those the +# kernel was constructed with, which backends can't drop by implementing `compiler_options`. +@inline function with_kernel_options(compile::C, kernel::Kernel, args...) where {C} + return compile(args...; compiler_options(kernel)..., kernel.options...) +end + static_ndrange(kernel::Kernel) = ndrange(kernel) <: StaticSize ? get(ndrange(kernel)) : nothing # the product of `dims`, saturated at `typemax(Int)` @@ -171,10 +177,10 @@ function launch_kernel( kernel = if skip_bounds_check(b) # hide the check type from inference, so that the lookup compiles once for both compiled_tt = Base.compilerbarrier(:type, unchecked ? without_bounds_check(tt) : tt)::Type - kernel_function_as(b, obj.f, compiled_tt, tt; compiler_options(obj)...) + with_kernel_options(kernel_function_as, obj, b, obj.f, compiled_tt, tt) else # infer the kernel's type, avoiding dynamic dispatch in the rest of the launch - KI.kernel_function(b, obj.f, tt; compiler_options(obj)...) + with_kernel_options(KI.kernel_function, obj, b, obj.f, tt) end # tune the workgroup size, keeping the context type (and thus the kernel) the same @@ -198,7 +204,7 @@ function launch_kernel( extent = split_extent(size(cartesian(range)), items) if extent !== nothing && split_launch(b, launch, kernel) full_tt = Base.compilerbarrier(:type, without_bounds_check(tt))::Type - full = kernel_function_as(b, obj.f, full_tt, tt; compiler_options(obj)...) + full = with_kernel_options(kernel_function_as, obj, b, obj.f, full_tt, tt) if prod(items) <= KI.max_work_group_size(full) launch_split(full, kernel, extent, groups, items, prepend(ctx, kernel_args)) return nothing diff --git a/src/macros.jl b/src/macros.jl index 2619ef319..e16395cf4 100644 --- a/src/macros.jl +++ b/src/macros.jl @@ -1,5 +1,11 @@ import MacroTools: splitdef, combinedef, isexpr, postwalk +# The static workgroup size and ndrange of a kernel constructed with the sizes `sizes` +kernel_sizes() = (DynamicSize(), DynamicSize()) +kernel_sizes(size) = (StaticSize(size), DynamicSize()) +kernel_sizes(size, range) = (StaticSize(size), StaticSize(range)) +kernel_sizes(size::_Size, range::_Size) = (size, range) + function find_return(stmt) result = Ref(false) postwalk(stmt) do expr @@ -89,17 +95,15 @@ function __kernel(expr, __source__::LineNumberNode, __module__::Module, force_in push!(queries, :($gpu_name(::$CollectivesQuery) = true)) end - # create constructor functions - _name = Symbol(:_, name) + # create constructor functions. a single method takes the sizes and the keywords: a local + # function with several keyword methods would box its keyword bodies. the varargs are + # typed, so that the method is specialized when called through dynamic dispatch too. types + # are interpolated so that the caller's bindings can't shadow them, except `Vararg`, + # which lowering only recognizes by name. constructors = quote if $(name isa Symbol ? :(!@isdefined($name)) : true) - function $_name(dev::Dev, sz::S, range::NDRange) where {Dev, S <: $_Size, NDRange <: $_Size} - return $construct(dev, sz, range, $gpu_name) - end - Core.@__doc__ $name(dev) = $_name(dev, $DynamicSize(), $DynamicSize()) - $name(dev, size) = $_name(dev, $StaticSize(size), $DynamicSize()) - $name(dev, size, range) = $_name(dev, $StaticSize(size), $StaticSize(range)) - $name(dev, size::$_Size, range::$_Size) = $_name(dev, size, range) + Core.@__doc__ $name(dev, sizes::Vararg{$Any, N}; sub_group_size::$Union{$Nothing, $Integer} = nothing) where {N} = + $construct(dev, $kernel_sizes(sizes...)..., $gpu_name; sub_group_size) $(queries...) end end diff --git a/src/pocl/backend.jl b/src/pocl/backend.jl index b44d768f8..1ac8266dd 100644 --- a/src/pocl/backend.jl +++ b/src/pocl/backend.jl @@ -203,12 +203,21 @@ function KI.kernel_function(backend::POCLBackend, f::F, tt::TT = Tuple{}; kwargs end Base.@nospecializeinfer function KA.kernel_function_as( - backend::POCLBackend, f::F, @nospecialize(compiled_tt::Type), tt::TT; name = nothing, kwargs... + backend::POCLBackend, f::F, @nospecialize(compiled_tt::Type), tt::TT; + name = nothing, sub_group_size = nothing, kwargs... ) where {F, TT} - # the sub-group width defaults to the one `KI.sub_group_size` reports. it is determined - # when creating the compiler configuration, since passing it here would make the keyword - # arguments' type depend on the device, and the call to `clfunction` dynamic. - kernel = clfunction(clconvert(f), tt, compiled_tt; name, kwargs...) + # without a request, kernels are compiled for the first of `KI.sub_group_sizes`. that + # width is determined when creating the compiler configuration, since passing it here + # would make the keyword arguments' type depend on the device, and the call to + # `clfunction` dynamic. a requested width is checked here: `clfunction` also accepts + # widths past 64, which don't keep the guarantees of `KI.sub_group_sizes`, and takes + # `nothing` to mean no `intel_reqd_sub_group_size`, which lets PoCL pick the width. + kernel = if sub_group_size === nothing + clfunction(clconvert(f), tt, compiled_tt; name, kwargs...) + else + check_sub_group_size(backend, sub_group_size) + clfunction(clconvert(f), tt, compiled_tt; name, sub_group_size = Int(sub_group_size), kwargs...) + end kern = POCLKernel(kernel, f) return KI.Kernel{POCLBackend, typeof(kern)}(backend, kern) end @@ -254,7 +263,14 @@ KI.max_work_group_size(::POCLBackend)::Int = device_limits().max_work_group_size KI.max_work_group_dims(::POCLBackend)::NTuple{3, Int} = device_limits().max_work_group_dims # the grid is only limited by the size of `size_t` KI.max_num_groups(::POCLBackend)::NTuple{3, Int} = (typemax(Int), typemax(Int), typemax(Int)) -KI.sub_group_size(::POCLBackend)::Int = device_limits().sub_group_size +KI.sub_group_sizes(::POCLBackend)::Tuple{Vararg{Int}} = POCL.session().sub_group_sizes + +@noinline function check_sub_group_size(backend::POCLBackend, width) + sizes = KI.sub_group_sizes(backend) + width in sizes || + throw(ArgumentError("Sub-group size $(repr(width)) is not supported by this device, which supports $sizes")) + return +end KI.multiprocessor_count(::POCLBackend)::Int = device_limits().compute_units # each work-group runs on one thread, which loops over (and vectorizes across) its diff --git a/src/pocl/compiler/compilation.jl b/src/pocl/compiler/compilation.jl index 36bab0662..6ad72408a 100644 --- a/src/pocl/compiler/compilation.jl +++ b/src/pocl/compiler/compilation.jl @@ -190,7 +190,7 @@ end The GPUCompiler configuration for compiling kernels for `dev`, cached per device and keyword arguments. Besides those of `CompilerConfig` (`kernel`, `name`, `always_inline`, `debug_level`) and `sub_group_size` (the sub-group width to require, or `nothing` for none, -defaulting to the width `KI.sub_group_size` reports), it takes: +defaulting to the first of `KI.sub_group_sizes`), it takes: - `atomics`: override the atomic capabilities GPUCompiler may select directly. This replaces the whole device-derived `SPIRVAtomics` (see `spirv_atomics`), and defaults to diff --git a/src/pocl/pocl.jl b/src/pocl/pocl.jl index e5c24c9ea..4c16a967f 100644 --- a/src/pocl/pocl.jl +++ b/src/pocl/pocl.jl @@ -23,6 +23,8 @@ mutable struct Session compute_units::Int, preferred_work_group_size_multiple::Int, fp16::Bool, fp64::Bool, } + # the widths kernels can request; not one of `limits`, which would make it abstract + const sub_group_sizes::Tuple{Vararg{Int}} # duration threshold in cycle counter ticks for long launches (see `host_dispatch`) const host_kernel_long_ticks::UInt64 # serial-duration threshold in ticks for small launches (see `host_schedule`) @@ -54,13 +56,23 @@ function ticks_per_ns() return (c1 - c0) / (t1 - t0) end -# the sub-group width kernels are compiled for, or `nothing` if the device has no sub-groups. -# POCL can technically support any sub-group size; prefer the common GPU ones, and only -# widths of up to 64, so that `KI.sub_group_ballot` (a `UInt64` mask) covers every lane. -function default_sub_group_size(device::cl.Device) +# the sub-group widths kernels can request: only those of up to 64, so that +# `KI.sub_group_ballot` (a `UInt64` mask) covers every lane. PoCL can technically support any +# sub-group size; the first, which kernels are compiled for without a request, is the most +# common GPU one it supports. +function supported_sub_group_sizes(device::cl.Device) sg_sizes = filter(<=(64), device.sub_group_sizes::Tuple{Vararg{Int}}) - common = filter(in(sg_sizes), Int[32, 64, 16, sg_sizes...]) - return isempty(common) ? nothing : first(common) + i = findfirst(in(sg_sizes), (32, 64, 16)) + i === nothing && return sg_sizes + W = (32, 64, 16)[i] + return (W, filter(!=(W), sg_sizes)...) +end + +# the sub-group width kernels are compiled for without a request, or `nothing` if the device +# has no sub-groups +function default_sub_group_size(device::cl.Device) + sg_sizes = supported_sub_group_sizes(device) + return isempty(sg_sizes) ? nothing : first(sg_sizes) end function Session() @@ -106,8 +118,10 @@ function Session() # 1 µs, compared with tens of nanoseconds to time a launch host_kernel_short_ticks = round(UInt64, 1_000 * rate) + sub_group_sizes = supported_sub_group_sizes(device) + return Session( - platform, device, context, limits, host_kernel_long_ticks, + platform, device, context, limits, sub_group_sizes, host_kernel_long_ticks, host_kernel_serial_ticks, host_kernel_short_ticks ) end diff --git a/test/hostinterface.jl b/test/hostinterface.jl index 5693d6e4e..5ec009d0f 100644 --- a/test/hostinterface.jl +++ b/test/hostinterface.jl @@ -58,7 +58,7 @@ function hostinterface_testsuite(_backend, AT) @test KI.multiprocessor_count(backend) isa Int @test KI.supports_subgroups(backend) isa Bool if KI.supports_subgroups(backend) - @test KI.sub_group_size(backend) isa Int + @test KI.sub_group_sizes(backend) isa Tuple{Vararg{Int}} end @test KI.supports_shuffle(backend, Float32) isa Bool diff --git a/test/launch.jl b/test/launch.jl index 631c84408..d21df1627 100644 --- a/test/launch.jl +++ b/test/launch.jl @@ -109,6 +109,10 @@ default_launcher(kernel, args...; ndrange, workgroupsize = nothing) = # Check every `@index` flavour against the layout KernelAbstractions defines: groups and # work-items are numbered column-major, and the global index is `(g-1)*groupsize + l`. +@kernel function launch_sub_group_size!(out) + out[@index(Global)] = KI.get_max_sub_group_size() +end + function check_indices(launcher, backend, AT, kernel, ndrange; workgroupsize = nothing) ranges = map(r -> r isa Integer ? (1:r) : r, ndrange) N = length(ranges) @@ -226,6 +230,38 @@ function launch_testsuite(backend, AT; launcher = default_launcher, skip_tests = @test all(==(3), Array(A)) end + @testset "requested sub-group width" begin + out = AT(zeros(Int, 100)) + sizes = KI.supports_subgroups(backend()) ? KI.sub_group_sizes(backend()) : () + function widths(kernel; kwargs...) + fill!(out, 0) + kernel(out; kwargs...) + synchronize(backend()) + return Array(out) + end + for W in sizes + kernel = launch_sub_group_size!(backend(); sub_group_size = W) + @test all(==(W), widths(kernel; ndrange = length(out))) + @test all(==(W), widths(similar(kernel, kernel.f); ndrange = length(out))) + # with static sizes and a partial workgroup, launched repeatedly, which some + # backends split into launches of differently compiled kernels + kernel = launch_sub_group_size!(backend(), 64, length(out); sub_group_size = W) + for _ in 1:3 + @test all(==(W), widths(kernel)) + end + end + # `nothing` requests no width + @test typeof(launch_sub_group_size!(backend(); sub_group_size = nothing)) == + typeof(launch_sub_group_size!(backend())) + if KI.supports_subgroups(backend()) + kernel = launch_sub_group_size!(backend(); sub_group_size = nothing) + @test all(>(0), widths(kernel; ndrange = length(out))) + end + # a width that isn't offered + W = 2 * maximum(sizes; init = 32) + @test_throws ArgumentError launch_sub_group_size!(backend(); sub_group_size = W)(out; ndrange = 1) + end + @testset "synchronize with padding lanes" begin for (shape, wgs) in (((37,), (8,)), ((7, 6), (4, 4)), ((5, 3, 3), (2, 2, 2)), ((8, 6), (4, 3))) A = AT(zeros(Int, shape)) diff --git a/test/runtests.jl b/test/runtests.jl index e8c08f10f..765122b7c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -352,7 +352,7 @@ end include("bfloat16.jl") -# the sub-group width kernels are compiled for is the one `KI.sub_group_size` reports +# kernels without a requested sub-group width are compiled for the preferred one # (PoCL folds `get_max_sub_group_size` to that constant itself, see pocl/pocl#2375) function max_sub_group_size_kernel(out) out[1] = KernelAbstractions.KernelInterface.get_max_sub_group_size()