diff --git a/.buildkite/pipeline.yml b/.buildkite/pipeline.yml index 900aef54a..994d77f02 100644 --- a/.buildkite/pipeline.yml +++ b/.buildkite/pipeline.yml @@ -2,7 +2,7 @@ # pull requests skip them, unless selected by name in the last commit message: `[only cuda]`, # `[only metal, oneapi]`, `[only tests]` for all tests, or `[only benchmarks]`. `[skip amdgpu]` # or `[skip tests]` does the opposite. (`opencl` selects the OpenCL.jl tests, on PoCL and on -# CUDA hardware.) +# CUDA hardware; `enzyme` selects the tests of the Enzyme extension on the back ends.) # # Pull requests only test the oldest and newest supported Julia release; the releases in # between are tested on branch builds, or on pull requests when selected with `[only julia]` @@ -61,6 +61,119 @@ steps: (build.message =~ /\[only [^\]]*(tests|cuda|julia)/ || build.message !~ /\[only / && build.pull_request.id == null) + # The Enzyme extension on the GPU back ends, whose own test suites don't run + # test/extensions/enzyme.jl. The back ends implement `EnzymeCore.compiler_job_from_backend`. + - &cuda_enzyme + label: "CUDA Enzyme Julia {{matrix.version}}" + matrix: + setup: + version: + - "1.10" + - "1.13" + plugins: + - JuliaCI/julia#v1: + version: "{{matrix.version}}" + - JuliaCI/julia-coverage#v1: + codecov: true + command: | + 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 + echo "--- :julia: Developing CUDA" + julia .buildkite/develop_backend.jl https://github.com/JuliaGPU/CUDA.jl main \ + 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 + Pkg.add(["Enzyme", "Test"])' || exit 3 + + julia --code-coverage=@$(pwd) -e 'println("+++ :julia: Running tests") + include(joinpath(".buildkite", "check_sources.jl")) + using CUDA + include(joinpath("test", "extensions", "enzyme.jl")) + @testset "Enzyme" begin + enzyme_testsuite(CUDABackend, CuArray, true) + end' + agents: + queue: "cuda" + if: | + build.message !~ /\[skip [^\]]*(tests|cuda|enzyme)/ && + (build.message =~ /\[only [^\]]*(tests|cuda|enzyme)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + soft_fail: + - exit_status: 3 + env: + JULIA_PROJECT: "@cuda_enzyme" + + # intermediate releases, not tested on pull requests + - <<: *cuda_enzyme + matrix: + setup: + version: + - "1.11" + - "1.12" + if: | + build.message !~ /\[skip [^\]]*(tests|cuda|enzyme|julia)/ && + (build.message =~ /\[only [^\]]*(tests|cuda|enzyme|julia)/ || + build.message !~ /\[only / && build.pull_request.id == null) + + - &amdgpu_enzyme + label: "AMDGPU Enzyme Julia {{matrix.version}}" + matrix: + setup: + version: + - "1.10" + - "1.13" + plugins: + - JuliaCI/julia#v1: + version: "{{matrix.version}}" + - JuliaCI/julia-coverage#v1: + codecov: true + command: | + 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 + 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 -e 'println("--- :julia: Adding Enzyme") + using Pkg + Pkg.add(["Enzyme", "Test"])' || exit 3 + + julia --code-coverage=@$(pwd) -e 'println("+++ :julia: Running tests") + include(joinpath(".buildkite", "check_sources.jl")) + using AMDGPU + include(joinpath("test", "extensions", "enzyme.jl")) + @testset "Enzyme" begin + enzyme_testsuite(ROCBackend, ROCArray, true) + end' + agents: + queue: "rocm" + if: | + build.message !~ /\[skip [^\]]*(tests|amdgpu|enzyme)/ && + (build.message =~ /\[only [^\]]*(tests|amdgpu|enzyme)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + soft_fail: + - exit_status: 3 + env: + JULIA_PROJECT: "@amdgpu_enzyme" + + # intermediate releases, not tested on pull requests + - <<: *amdgpu_enzyme + matrix: + setup: + version: + - "1.11" + - "1.12" + if: | + build.message !~ /\[skip [^\]]*(tests|amdgpu|enzyme|julia)/ && + (build.message =~ /\[only [^\]]*(tests|amdgpu|enzyme|julia)/ || + build.message !~ /\[only / && build.pull_request.id == null) + - &metal label: "Metal Julia {{matrix.version}}" matrix: @@ -158,6 +271,63 @@ steps: (build.message =~ /\[only [^\]]*(tests|oneapi|julia)/ || build.message !~ /\[only / && build.pull_request.id == null) + - &oneapi_enzyme + label: "oneAPI Enzyme Julia {{matrix.version}}" + matrix: + setup: + version: + - "1.10" + - "1.13" + plugins: + - JuliaCI/julia#v1: + version: "{{matrix.version}}" + - JuliaCI/julia-coverage#v1: + codecov: true + command: | + 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 + 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 -e 'println("--- :julia: Adding Enzyme") + using Pkg + Pkg.add(["Enzyme", "Test"])' || exit 3 + + julia --code-coverage=@$(pwd) -e 'println("+++ :julia: Running tests") + include(joinpath(".buildkite", "check_sources.jl")) + using oneAPI + include(joinpath("test", "extensions", "enzyme.jl")) + @testset "Enzyme" begin + T = KernelAbstractions.supports_float64(oneAPIBackend()) ? Float64 : Float32 + enzyme_testsuite(oneAPIBackend, oneArray, true, T) + end' + agents: + queue: "oneapi" + if: | + build.message !~ /\[skip [^\]]*(tests|oneapi|enzyme)/ && + (build.message =~ /\[only [^\]]*(tests|oneapi|enzyme)/ || + build.message !~ /\[only / && !build.pull_request.draft) + timeout_in_minutes: 120 + soft_fail: + - exit_status: 3 + env: + JULIA_PROJECT: "@oneapi_enzyme" + + # intermediate releases, not tested on pull requests + - <<: *oneapi_enzyme + matrix: + setup: + version: + - "1.11" + - "1.12" + if: | + build.message !~ /\[skip [^\]]*(tests|oneapi|enzyme|julia)/ && + (build.message =~ /\[only [^\]]*(tests|oneapi|enzyme|julia)/ || + build.message !~ /\[only / && build.pull_request.id == null) + - &amdgpu label: "AMDGPU Julia {{matrix.version}}" matrix: diff --git a/Project.toml b/Project.toml index 6eb0b7f13..ca145e1f6 100644 --- a/Project.toml +++ b/Project.toml @@ -29,6 +29,7 @@ pocl_standalone_jll = "54f56a70-6062-5590-a942-1226658f6c83" [weakdeps] AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" +EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Metal = "dde4c033-4e86-420c-a63e-0dd931031962" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" @@ -40,6 +41,7 @@ KernelInterface = {path = "lib/KernelInterface"} [extensions] AMDGPUExt = "AMDGPU" +EnzymeExt = "EnzymeCore" LinearAlgebraExt = "LinearAlgebra" MetalExt = "Metal" SparseArraysExt = "SparseArrays" @@ -50,6 +52,7 @@ oneAPIExt = "oneAPI" AMDGPU = "2" Adapt = "0.4, 1.0, 2.0, 3.0, 4" Atomix = "1.5" +EnzymeCore = "0.8.25" GPUCompiler = "2.20" GPUToolbox = "3.6" KernelInterface = "0.4" @@ -75,5 +78,6 @@ oneAPI = "2" pocl_standalone_jll = "7.2.3" [extras] +EnzymeCore = "f151be2c-9106-41f4-ab19-57ee4f262869" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" diff --git a/ext/EnzymeCore08Ext.jl b/ext/EnzymeCore08Ext.jl new file mode 100644 index 000000000..fbffd3edf --- /dev/null +++ b/ext/EnzymeCore08Ext.jl @@ -0,0 +1,250 @@ +# Split reverse mode of the kernel body, with the settings of `config` (runtime activity, strong zero). +split_mode(config, ModifiedBetween) = + EnzymeRules.set_config(ReverseSplitModified(ReverseSplitWithPrimal, ModifiedBetween), config) + +_unwrap_const_type(arg) = arg +_unwrap_const_type(arg::Const{<:Type}) = arg.val +_rewrap_const_type(arg) = arg +_rewrap_const_type(::Type{T}) where {T} = Const{Type{T}}(T) + +function fwd(ctx, config, f, args...) + # no argument is `@Const`: the kernel's own arguments are wrapped in annotations + ctx isa ConstArgs && return nothing + args = map(_rewrap_const_type, args) + EnzymeCore.autodiff_deferred(EnzymeRules.set_config(Forward, config), Const(f), Const{Nothing}, Const(ctx), args...) + return nothing +end + +function EnzymeRules.forward( + config, + func::Const{<:Kernel}, + ::Type{Const{Nothing}}, + args...; + ndrange = nothing, + workgroupsize = nothing, + ) + kernel = func.val + f = kernel.f + fwd_kernel = similar(kernel, fwd) + + # `Const{Type{T}}` is not a bitstype, so it cannot be passed to kernels. + # Pass the type itself, and re-wrap it as `Const` in the kernel (`fwd`). + args = map(_unwrap_const_type, args) + return fwd_kernel(config, f, args...; ndrange, workgroupsize) +end + +# The context that launching `aug_fwd` or `rev` on the backend of `kernel` creates, as the +# kernel receives it (see `launch_tuple`). The tape type depends on its type. +function _enzyme_mkcontext(kernel::Kernel, ndrange, workgroupsize, iterspace) + launch = select_launch(kernel, workgroupsize, iterspace) + return argconvert(kernel, mkcontext(kernel, ndrange, iterspace, launch)) +end + +# A launch whose workgroups cover the ndrange gets a context without the bounds check, which +# only differs in its type. The kernel body is differentiated with the checked one, so that +# the tape type doesn't depend on the launch. +@inline checked_context(ctx::CompilerMetadata{NDRange, DynamicCheck}) where {NDRange} = ctx +@inline checked_context(ctx::CompilerMetadata{NDRange}) where {NDRange} = + CompilerMetadata{NDRange, DynamicCheck}(ctx.ndrange, ctx.iterspace; ctx.launch, ctx.subgroups) + +_augmented_return(::Kernel, subtape, arg_refs, tape_type) = + AugmentedReturn{Nothing, Nothing, Any}(nothing, nothing, (subtape, arg_refs, tape_type)) + +function _create_tape_kernel( + kernel::Kernel, + Mode, + FT, + ctxTy, + ndrange, + iterspace, + args2..., + ) + # For peeking at the TapeType we need to first construct a correct compilation job + # this requires the use of the device side representation of arguments. + # So we convert the arguments here, this is a bit wasteful since the `aug_kernel` call + # will later do the same. + dev_args2 = ((argconvert(kernel, a) for a in args2)...,) + dev_TT = map(Core.Typeof, dev_args2) + + job = + EnzymeCore.compiler_job_from_backend(backend(kernel), typeof(() -> return), Tuple{}) + TapeType = EnzymeCore.tape_type( + job, + Mode, + FT, + Const{Nothing}, + Const{ctxTy}, + dev_TT..., + ) + + # Allocate per thread + subtape = allocate(backend(kernel), TapeType, _ka_nthreads(ndrange, iterspace)) + + aug_kernel = similar(kernel, aug_fwd) + return TapeType, subtape, aug_kernel +end + +function aug_fwd( + ctx, + f::FT, + mode::Mode, + subtape, + ::Val{TapeType}, + args..., + ) where {Mode, FT, TapeType} + ctx isa ConstArgs && return nothing + checked = checked_context(ctx) + # A2 = Const{Nothing} -- since f->Nothing + forward, _ = EnzymeCore.autodiff_deferred_thunk( + mode, + TapeType, + Const{Core.Typeof(f)}, + Const{Nothing}, + Const{Core.Typeof(checked)}, + map(Core.Typeof, args)..., + ) + + # On the GPU: F is a per thread function + # On the GPU: subtape::Vector + if __validindex(ctx) + I = __index_Global_Linear(ctx) + subtape[I] = forward(Const(f), Const(checked), args...)[1] + end + return nothing +end + +function rev( + ctx, + f::FT, + mode::Mode, + subtape, + ::Val{TapeType}, + args..., + ) where {Mode, FT, TapeType} + ctx isa ConstArgs && return nothing + checked = checked_context(ctx) + # XXX: TapeType and A2 as args to autodiff_deferred_thunk + _, reverse = EnzymeCore.autodiff_deferred_thunk( + mode, + TapeType, + Const{Core.Typeof(f)}, + Const{Nothing}, + Const{Core.Typeof(checked)}, + map(Core.Typeof, args)..., + ) + if __validindex(ctx) + I = __index_Global_Linear(ctx) + tp = subtape[I] + reverse(Const(f), Const(checked), args..., tp) + end + return nothing +end + +function EnzymeRules.augmented_primal( + config::RevConfig, + func::Const{<:Kernel}, + ::Type{Const{Nothing}}, + args::Vararg{Any, N}; + ndrange = nothing, + workgroupsize = nothing, + ) where {N} + kernel = func.val + f = kernel.f + + ndrange, workgroupsize, iterspace, dynamic = + launch_config(kernel, ndrange, workgroupsize) + ctx = _enzyme_mkcontext(kernel, ndrange, workgroupsize, iterspace) + ctxTy = Core.Typeof(ctx) + # TODO autodiff_deferred on the func.val + ModifiedBetween = Val((overwritten(config)[1], false, overwritten(config)[2:end]...)) + + FT = Const{Core.Typeof(f)} + + arg_refs = ntuple(Val(N)) do i + Base.@_inline_meta + if args[i] isa Active + error( + """ + Active kernel arguments not supported, got + \n$(typeof(args[i])) + \nFor argument $i of kernel + \n$(func.val). + """ + ) + else + nothing + end + end + args2 = ntuple(Val(N)) do i + Base.@_inline_meta + if args[i] isa Active + MixedDuplicated(args[i].val, arg_refs[i]) + else + args[i] + end + end + Mode = split_mode(config, ModifiedBetween) + TapeType, subtape, aug_kernel = _create_tape_kernel( + kernel, + Mode, + FT, + ctxTy, + ndrange, + iterspace, + args2..., + ) + aug_kernel(f, Mode, subtape, Val(TapeType), args2...; ndrange, workgroupsize) + + # TODO the fact that ctxTy is type unstable means this is all type unstable. + # Since custom rules require a fixed return type, explicitly cast to Any, rather + # than returning a AugmentedReturn{Nothing, Nothing, T} where T. + return _augmented_return(kernel, subtape, arg_refs, TapeType) +end + +function EnzymeRules.reverse( + config::RevConfig, + func::Const{<:Kernel}, + ::Type{<:EnzymeCore.Annotation}, + tape, + args::Vararg{Any, N}; + ndrange = nothing, + workgroupsize = nothing, + ) where {N} + subtape, arg_refs, tape_type = tape + + args2 = ntuple(Val(N)) do i + Base.@_inline_meta + if args[i] isa Active + MixedDuplicated(args[i].val, arg_refs[i]) + else + args[i] + end + end + + kernel = func.val + f = kernel.f + + ModifiedBetween = Val((overwritten(config)[1], false, overwritten(config)[2:end]...)) + Mode = split_mode(config, ModifiedBetween) + rev_kernel = similar(kernel, rev) + rev_kernel( + f, + Mode, + subtape, + Val(tape_type), + args2...; + ndrange, + workgroupsize, + ) + res = ntuple(Val(N)) do i + Base.@_inline_meta + if args[i] isa Active + arg_refs[i][] + else + nothing + end + end + # Reverse synchronization right after the kernel launch + synchronize(backend(kernel)) + return res +end diff --git a/ext/EnzymeExt.jl b/ext/EnzymeExt.jl new file mode 100644 index 000000000..b6e996edd --- /dev/null +++ b/ext/EnzymeExt.jl @@ -0,0 +1,96 @@ +module EnzymeExt +if isdefined(Base, :get_extension) + using EnzymeCore + using EnzymeCore.EnzymeRules +else + using ..EnzymeCore + using ..EnzymeCore.EnzymeRules +end + +import KernelAbstractions: + Kernel, + StaticSize, + launch_config, + allocate, + blocks, + workitems, + mkcontext, + select_launch, + CompilerMetadata, + ConstArgs, + DynamicCheck, + CPU, + argconvert, + supports_enzyme, + __fake_compiler_job, + backend, + __index_Group_Cartesian, + __index_Global_Linear, + __groupsize, + __groupindex, + __validindex, + Backend, + synchronize + +function EnzymeCore.compiler_job_from_backend( + b::Backend, + @nospecialize(F::Type), + @nospecialize(TT::Type), + ) + error( + "EnzymeCore.compiler_job_from_backend is not yet implemented for $(typeof(b)), please file an issue.", + ) +end + +import KernelAbstractions: POCLBackend +import KernelAbstractions: POCL + +function EnzymeCore.compiler_job_from_backend( + ::POCLBackend, + @nospecialize(F::Type), + @nospecialize(TT::Type), + ) + mi = POCL.GPUCompiler.methodinstance(F, TT) + return POCL.GPUCompiler.CompilerJob(mi, POCL.compiler_config(POCL.device())) +end + +EnzymeRules.inactive(::Type{StaticSize}, x...) = nothing + +# Number of threads a GPU launch runs, for sizing the per-thread tape. `ndrange` is `nothing` +# when the kernel was constructed with a static ndrange and launched without one, so recover +# the thread count from the resolved iteration space instead. +@inline function _ka_nthreads(ndrange, iterspace) + return ndrange === nothing ? + length(blocks(iterspace)) * length(workitems(iterspace)) : + prod(ndrange) +end + +include("EnzymeCore08Ext.jl") + +# Synchronize rules +# TODO: Right now we do the synchronization as part of the kernel launch in the augmented primal +# and reverse rules. This is not ideal, as we would want to launch the kernel in the reverse +# synchronize rule and then synchronize where the launch was. However, with the current +# kernel semantics this ensures correctness for now. +function EnzymeRules.augmented_primal( + config, + func::Const{typeof(synchronize)}, + ::Type{Const{Nothing}}, + backend::T, + ) where {T <: EnzymeCore.Annotation} + synchronize(backend.val) + return AugmentedReturn(nothing, nothing, nothing) +end + +function EnzymeRules.reverse( + config, + func::Const{typeof(synchronize)}, + ::Type{Const{Nothing}}, + tape, + backend, + ) + # noop for now + return (nothing,) +end + +end diff --git a/src/pocl/compiler/compilation.jl b/src/pocl/compiler/compilation.jl index d8c548632..c94298096 100644 --- a/src/pocl/compiler/compilation.jl +++ b/src/pocl/compiler/compilation.jl @@ -70,6 +70,15 @@ function GPUCompiler.finish_module!( job, mod, entry ) + # the built-ins of SPIRVIntrinsics don't free memory. Enzyme needs to know that to + # differentiate callers in reverse mode, and cannot tell from a declaration. + # XXX: SPIRVIntrinsics should declare them `nofree` + for f in mod.functions + if isempty(f.blocks) && contains(f.name, "__spirv_BuiltIn") + push!(f.function_attributes, EnumAttribute(:nofree)) + end + end + sg_size = job.config.params.sub_group_size if sg_size !== nothing entry.metadata["intel_reqd_sub_group_size"] = MDNode([ConstantInt(Int32(sg_size))]) diff --git a/src/pocl/pocl.jl b/src/pocl/pocl.jl index 8d707fd34..e5c24c9ea 100644 --- a/src/pocl/pocl.jl +++ b/src/pocl/pocl.jl @@ -157,7 +157,7 @@ end using GPUCompiler using LLVM, LLVM.Build, LLVM.Interop # not all of LLVM.IR, whose `context` would clash with ours -using LLVM.IR: BasicBlock, ConstantArray, ConstantInt, DILocation, GlobalVariable, LLVMType, +using LLVM.IR: BasicBlock, ConstantArray, ConstantInt, DILocation, EnumAttribute, GlobalVariable, LLVMType, MDNode, MD_invariant_load, MD_tbaa, MemoryEffects, StringAttribute, Value using SPIRV_LLVM_Backend_jll, SPIRV_Tools_jll using Adapt diff --git a/test/Project.toml b/test/Project.toml index 0fd1a6eba..e981e1f93 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -2,6 +2,7 @@ Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" BFloat16s = "ab4f0b2a-ad5b-11e8-123f-65d77653426b" +Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" FileCheck = "4e644321-382b-4b05-b0b6-5d23c3d944fb" GPUToolbox = "096a3bc2-3ced-46d0-87f4-dd12716f4bfc" InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240" @@ -23,4 +24,5 @@ KernelInterface = {path = "../lib/KernelInterface"} [compat] Aqua = "0.8" BFloat16s = "0.6" +Enzyme = "0.13.221" FileCheck = "1.2" diff --git a/test/extensions/enzyme.jl b/test/extensions/enzyme.jl new file mode 100644 index 000000000..8582eda53 --- /dev/null +++ b/test/extensions/enzyme.jl @@ -0,0 +1,131 @@ +using Test +using Enzyme +using KernelAbstractions + +@kernel function square!(A) + I = @index(Global, Linear) + @inbounds A[I] *= A[I] +end + +function square_caller(A, backend) + kernel = square!(backend) + kernel(A, ndrange = size(A)) + KernelAbstractions.synchronize(backend) + return +end + +# The ndrange is fixed when the kernel is constructed, so the launch does not pass one +function square_static_caller(A, backend) + kernel = square!(backend, 32, size(A)) + kernel(A) + KernelAbstractions.synchronize(backend) + return +end + +@kernel function mul!(A, B) + I = @index(Global, Linear) + @inbounds A[I] *= B +end + +function mul_caller(A, B, backend) + kernel = mul!(backend) + kernel(A, B, ndrange = size(A)) + KernelAbstractions.synchronize(backend) + return +end + +@kernel function scale_typed!(A, ::Type{T}) where {T} + I = @index(Global, Linear) + @inbounds A[I] *= T(2) +end + +function scale_typed_caller(A, ::Type{T}, backend) where {T} + kernel = scale_typed!(backend) + kernel(A, T, ndrange = size(A)) + KernelAbstractions.synchronize(backend) + return +end + +# `T` is the element type of the arrays, for back ends without `Float64` +function enzyme_testsuite(backend, ArrayT, supports_reverse = true, T = Float64) + @testset "kernels" begin + A = ArrayT{T}(undef, 64) + dA = ArrayT{T}(undef, 64) + + if supports_reverse + + A .= (1:1:64) + dA .= 1 + + Enzyme.autodiff(Reverse, square_caller, Duplicated(A, dA), Const(backend())) + @test all(dA .≈ (2:2:128)) + + A .= (1:1:64) + dA .= 1 + + Enzyme.autodiff(Reverse, square_static_caller, Duplicated(A, dA), Const(backend())) + @test all(dA .≈ (2:2:128)) + + # active arguments are not supported for kernels + A .= (1:1:64) + dA .= 1 + + @test_throws "Active kernel arguments not supported" Enzyme.autodiff( + Reverse, mul_caller, Duplicated(A, dA), Active(T(1.2)), Const(backend()) + ) + + # The strong zero setting is passed on to the kernel: the adjoint of `A[I] * B` + # with `B = Inf` and a zero adjoint of the result is `0 * Inf = NaN` without it + # and zero with it + A .= 1 + dA .= 0 + + Enzyme.autodiff(Reverse, mul_caller, Duplicated(A, dA), Const(T(Inf)), Const(backend())) + @test all(isnan, dA) + + if isdefined(Enzyme, :set_strong_zero) + A .= 1 + dA .= 0 + + Enzyme.autodiff(Enzyme.set_strong_zero(Reverse), mul_caller, Duplicated(A, dA), Const(T(Inf)), Const(backend())) + @test all(iszero, dA) + end + end + + A .= (1:1:64) + dA .= 1 + + Enzyme.autodiff(Forward, square_caller, Duplicated(A, dA), Const(backend())) + KernelAbstractions.synchronize(backend()) + @test all(dA .≈ 2:2:128) + + # Type arguments of kernels + A .= (1:1:64) + dA .= 1 + + Enzyme.autodiff(Forward, scale_typed_caller, Duplicated(A, dA), Const(T), Const(backend())) + KernelAbstractions.synchronize(backend()) + @test all(dA .≈ 2) + @test all(A .≈ 2:2:128) + + # The strong zero setting is passed on to the kernel: the tangent of `A[I] * B` with + # `B = Inf` in direction zero is `0 * Inf = NaN` without it and zero with it + A .= 1 + dA .= 0 + + Enzyme.autodiff(Forward, mul_caller, Duplicated(A, dA), Const(T(Inf)), Const(backend())) + KernelAbstractions.synchronize(backend()) + @test all(isnan, dA) + + # Strong zero is not available in the Enzyme versions for Julia < 1.10 + if isdefined(Enzyme, :set_strong_zero) + A .= 1 + dA .= 0 + + Enzyme.autodiff(Enzyme.set_strong_zero(Forward), mul_caller, Duplicated(A, dA), Const(T(Inf)), Const(backend())) + KernelAbstractions.synchronize(backend()) + @test all(iszero, dA) + end + end + return +end diff --git a/test/quality_assurance.jl b/test/quality_assurance.jl index 85b913efd..543bc5401 100644 --- a/test/quality_assurance.jl +++ b/test/quality_assurance.jl @@ -144,7 +144,9 @@ end function quality_assurance_testsuite() @testset "Aqua" begin Aqua.test_all( - KernelAbstractions + KernelAbstractions; + stale_deps = (; ignore = [:Enzyme, :EnzymeCore]), + deps_compat = (; ignore = [:Enzyme, :EnzymeCore]), ) end diff --git a/test/runtests.jl b/test/runtests.jl index 709611ab2..f833ae925 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1891,3 +1891,8 @@ end @test CPU() isa KernelAbstractions.GPU @test NewBackend <: KernelAbstractions.GPU end + +include("extensions/enzyme.jl") +@testset "Enzyme" begin + enzyme_testsuite(CPU, Array) +end