From ef2747e435c542392deb13c3617dfacd71b9abe2 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 20:30:42 +0000 Subject: [PATCH 1/2] Add the KernelAbstractions extension with the device kernel pass FiniteElementMethodKAExt (triggers KernelAbstractions, Adapt, GPUArrays, GPUArraysCore) prepares an emitted kernel Expr for a device: Float64 and Rational literals are retyped to the working precision, NaNMath.pow becomes a FEM-owned nanpow, library ccalls such as NaNMath.lgamma are refused, and the function is built in FEM's RuntimeGeneratedFunctions cache with drop_expr so it is isbits. Core gains only the device_kernel stub, which names the packages to load when the extension is absent. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: f7b46bdf-7cc3-44dd-b8a4-9205616ff6ac Agent-Review: unreviewed Co-authored-by: Claude Code --- Project.toml | 9 +++ ext/FiniteElementMethodKAExt.jl | 108 ++++++++++++++++++++++++++++++++ src/kernels.jl | 9 +++ test/Kernels/kernels.jl | 5 ++ 4 files changed, 131 insertions(+) create mode 100644 ext/FiniteElementMethodKAExt.jl diff --git a/Project.toml b/Project.toml index fc7c0189..983642b0 100644 --- a/Project.toml +++ b/Project.toml @@ -21,20 +21,29 @@ SymbolicUtils = "d1185830-fcd6-423d-90d6-eec64667417b" Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" [weakdeps] +Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b" +GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7" +GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" [extensions] FiniteElementMethodFerriteGmshExt = "FerriteGmsh" +FiniteElementMethodKAExt = ["KernelAbstractions", "Adapt", "GPUArrays", "GPUArraysCore"] [compat] ADTypes = "1.24" +Adapt = "4" AllocCheck = "0.2" DiffEqBase = "7.21" DomainSets = "0.7, 0.8" Ferrite = "1.7" FerriteGmsh = "1.5" ForwardDiff = "1.4" +GPUArrays = "11" +GPUArraysCore = "0.2" Gmsh = "0.3" +KernelAbstractions = "0.9" LinearAlgebra = "1.10" ModelingToolkit = "11.34" LinearSolve = "5" diff --git a/ext/FiniteElementMethodKAExt.jl b/ext/FiniteElementMethodKAExt.jl new file mode 100644 index 00000000..160e9cb1 --- /dev/null +++ b/ext/FiniteElementMethodKAExt.jl @@ -0,0 +1,108 @@ +module FiniteElementMethodKAExt + +using FiniteElementMethod: FiniteElementMethod +using KernelAbstractions: KernelAbstractions +using RuntimeGeneratedFunctions: RuntimeGeneratedFunction, drop_expr + +# NaNMath is not a dependency, so its functions are recognised by module and function name. +callee(f::Function) = (parentmodule(f), nameof(f)) +callee(g::GlobalRef) = (g.mod, g.name) +callee(_) = nothing +function callee_is(c, mod, name) + m = callee(c) + return m !== nothing && nameof(m[1]) === mod && m[2] === name +end + +# Library ccalls with no device implementation (NaNMath 1.1.5, SpecialFunctions 2): GPUCompiler rejects them. +const NO_DEVICE_METHOD = Set( + [ + (:NaNMath, :lgamma); + [(:SpecialFunctions, f) for f in (:erfc, :erfcx, :erfi, :dawson, :besselj0, :besselj1, :bessely0, :bessely1)] + ] +) + +# `NaNMath.pow` as NaNMath 1.1.5 implements it in Julia; earlier NaNMath releases call libm, which no device has. It is +# NaN for a negative base with a non-integer exponent, where `^` throws a DomainError on the host. +function nanpow(x::Real, y::Real) + fx, fy = map(float, promote(x, y)) + return fx >= 0 || isinteger(y) ? fx^fy : oftype(fx, NaN) +end +nanpow(x::Real, y::Integer) = x^y +nanpow(x, y) = x^y + +# The kernel's own argument named `T` (the time slot) is never touched: only literal values are replaced. +retype(ex, ::Type) = ex +retype(x::Union{Float64, Rational}, ::Type{T}) where {T} = T(x) +function retype(ex::Expr, ::Type{T}) where {T} + args = Any[retype(a, T) for a in ex.args] + ex.head === :call && callee_is(args[1], :NaNMath, :pow) && return Expr(:call, nanpow, args[2:end]...) + return Expr(ex.head, args...) +end + +function device_violations(kernel::Expr, ::Type{T}) where {T} + found = String[] + function visit(e) + e isa Float64 && T !== Float64 && push!(found, "the Float64 literal $e") + e isa Expr || return + e.head in (:->, :function) && push!(found, "a closure") + (e.head === :foreigncall || (e.head === :call && e.args[1] in (:ccall, :cglobal))) && push!(found, "a ccall") + if e.head === :call + c = callee(e.args[1]) + callee_is(e.args[1], :NaNMath, :pow) && push!(found, "NaNMath.pow, a libm ccall before NaNMath 1.1.5") + c !== nothing && (nameof(c[1]), c[2]) in NO_DEVICE_METHOD && + push!(found, "$(c[1]).$(c[2]), a library ccall with no device implementation") + end + return foreach(visit, e.args) + end + # The kernel is itself a function expression; only functions inside its body are closures. + foreach(visit, kernel.head in (:->, :function) ? kernel.args : (kernel,)) + return unique(found) +end + +function FiniteElementMethod.device_kernel(ex::Expr, ::Type{T}) where {T} + T <: AbstractFloat || throw(ArgumentError("the precision of a device kernel must be a floating-point type, got $T")) + kernel = retype(ex, T) + found = device_violations(kernel, T) + isempty(found) || throw(ArgumentError("a generated kernel cannot run on a device: it contains " * join(found, ", "))) + # FiniteElementMethod's own cache and context, as Symbolics.build_function uses for the host kernels. + f = drop_expr(RuntimeGeneratedFunction(FiniteElementMethod, FiniteElementMethod, kernel)) + @assert isbits(f) + return f +end + +# Calls into modules other than these are user-registered symbolic functions, which may not compile for a device; +# that is known only when the first launch compiles the kernel. +const DEVICE_SAFE_MODULES = (Base, Core, FiniteElementMethod, @__MODULE__) +function foreign_callees(ex) + found = Set{String}() + function visit(e) + e isa Expr || return + if e.head === :call + c = callee(e.args[1]) + c === nothing || Base.moduleroot(c[1]) in DEVICE_SAFE_MODULES || nameof(c[1]) === :NaNMath || + push!(found, "$(c[1]).$(c[2])") + end + return foreach(visit, e.args) + end + visit(ex) + return sort!(collect(found)) +end + +function kernel_compile_error(backend::KernelAbstractions.Backend, callees, err) + return ArgumentError( + "a generated kernel failed to compile for $(nameof(typeof(backend))); it calls the user functions " * + join(callees, ", ") * ", which must be GPU-compilable (no allocation, Dict, String or ccall). " * + "Original error: " * first(split(sprint(showerror, err), '\n')) + ) +end + +function launch_checked(launch, backend::KernelAbstractions.Backend, callees) + try + return launch() + catch err + isempty(callees) && rethrow() + throw(kernel_compile_error(backend, callees, err)) + end +end + +end # module diff --git a/src/kernels.jl b/src/kernels.jl index d738a4e7..3851dfe1 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -192,3 +192,12 @@ function emit_strong(analysis; expression = Val(false)) s = analysis.slots return Tuple(compile(assert_differentiated(e), (s.U, s.G, s.Ud, s.H, s.X, s.T, s.P); expression) for e in analysis.strong) end + +# The method is in the FiniteElementMethodKAExt extension, which loads with KernelAbstractions, Adapt, GPUArrays and +# GPUArraysCore. +device_kernel(ex, T) = throw( + ArgumentError( + "device kernels need the KernelAbstractions extension of FiniteElementMethod; " * + "load KernelAbstractions, Adapt, GPUArrays and GPUArraysCore" + ) +) diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index 4c5f0324..ae406833 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -223,3 +223,8 @@ end end @test worst ≤ 1.0e-13 end + +@testset "device kernels say which packages load the KernelAbstractions extension when it is absent" begin + ex = first(emit_kernels(weak_form(case_i()); expression = Val(true))).coeffs + @test_throws "load KernelAbstractions, Adapt, GPUArrays and GPUArraysCore" FiniteElementMethod.device_kernel(ex, Float32) +end From cca3a96268a07d245a85c9592d0dcb36151a87b4 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 20:30:42 +0000 Subject: [PATCH 2/2] Add the GPU test group: device pass on KA.CPU, JLArrays and AMDGPU Kernels of real PDESystems go through the device pass and a KernelAbstractions kernel on KA.CPU() and JLArrays, and must match the host Float64 kernels (Float32 within 1e-6). test/GPU/vendor/amdgpu runs the same files on ROCBackend by hand, including a Dict-allocating registered function whose compile failure must name it. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-opus-5-5 Agent-Session: f7b46bdf-7cc3-44dd-b8a4-9205616ff6ac Agent-Review: unreviewed Co-authored-by: Claude Code --- test/GPU/Project.toml | 41 +++++++ test/GPU/README.md | 51 +++++++++ test/GPU/backends.jl | 26 +++++ test/GPU/common/backend.jl | 26 +++++ test/GPU/common/cases.jl | 111 +++++++++++++++++++ test/GPU/common/harness.jl | 72 ++++++++++++ test/GPU/devicepass.jl | 82 ++++++++++++++ test/GPU/vendor/amdgpu/LocalPreferences.toml | 3 + test/GPU/vendor/amdgpu/Project.toml | 41 +++++++ test/GPU/vendor/amdgpu/runtests.jl | 37 +++++++ test/test_groups.toml | 5 + 11 files changed, 495 insertions(+) create mode 100644 test/GPU/Project.toml create mode 100644 test/GPU/README.md create mode 100644 test/GPU/backends.jl create mode 100644 test/GPU/common/backend.jl create mode 100644 test/GPU/common/cases.jl create mode 100644 test/GPU/common/harness.jl create mode 100644 test/GPU/devicepass.jl create mode 100644 test/GPU/vendor/amdgpu/LocalPreferences.toml create mode 100644 test/GPU/vendor/amdgpu/Project.toml create mode 100644 test/GPU/vendor/amdgpu/runtests.jl diff --git a/test/GPU/Project.toml b/test/GPU/Project.toml new file mode 100644 index 00000000..6aba3199 --- /dev/null +++ b/test/GPU/Project.toml @@ -0,0 +1,41 @@ +[deps] +Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf" +Ferrite = "c061ca5d-56c9-439f-9c0e-210fe06d3992" +FiniteElementMethod = "e08948db-0ae8-498a-9b98-73fc7f237ce3" +GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7" +GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" +GenericSparseArrays = "da3fe0eb-88a8-4d14-ae1a-857c283e9c70" +JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" +NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +RuntimeGeneratedFunctions = "7e49a35a-f44a-4d26-94aa-eba1b4ca6b47" +SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[sources] +FiniteElementMethod = {path = "../.."} + +[compat] +Adapt = "4" +DomainSets = "0.7, 0.8" +Ferrite = "1.7" +GPUArrays = "11" +GPUArraysCore = "0.2" +GenericSparseArrays = "0.1" +JLArrays = "0.3.3" +KernelAbstractions = "0.9" +LinearAlgebra = "1" +ModelingToolkit = "11" +NaNMath = "1.1.5" +Random = "1" +RuntimeGeneratedFunctions = "0.5.12" +SafeTestsets = "0.1" +SparseArrays = "1" +Symbolics = "7" +Test = "1" diff --git a/test/GPU/README.md b/test/GPU/README.md new file mode 100644 index 00000000..e622ea8b --- /dev/null +++ b/test/GPU/README.md @@ -0,0 +1,51 @@ +# GPU group + +Tests of `FiniteElementMethodKAExt`, the KernelAbstractions extension. It loads when KernelAbstractions, Adapt, +GPUArrays and GPUArraysCore are all loaded. The group is opt-in (`in_all = false`) and runs on Julia 1 only, because +`Project.toml` develops the package through `[sources]`, which Julia 1.10 ignores. + +```sh +GROUP=GPU julia --project=. -e 'using Pkg; Pkg.test()' +``` + +## What is tested + +The kernels come from real `PDESystem`s (`common/cases.jl`). They cover mass, bilinear and source coefficients, a +Neumann facet kernel, SUPG cell coefficients with the element size, a nonlinear `f` and `tangent`, `NaNMath.pow` with +constant and symbolic exponents, time-dependent Dirichlet data, and a registered function. For this layer the +end-to-end check runs from the `PDESystem` to its emitted kernels, through the device pass, to a KernelAbstractions +kernel whose result must equal the host Float64 kernel. End-to-end tests at the level of `discretize` arrive with +device assembly. + +- `devicepass.jl` runs on the host. It checks that no emitted kernel keeps a Float64 literal, a closure, a ccall or + `NaNMath.pow` after the pass. A Float32 kernel returns no Float64 and stays within 1e-6 relative of the Float64 + kernel. `NaNMath.lgamma` and the other library ccalls are refused when the kernel is prepared, and the error for a + user function that fails to compile names that function. +- `backends.jl` evaluates every prepared kernel in a `@kernel` on `KernelAbstractions.CPU()` and on JLArrays, in + Float32 and Float64. + +## What the CPU backends cannot catch + +`KernelAbstractions.CPU()` and JLArrays test host discipline only. JLArrays 0.3.3 is the newest release that accepts +KernelAbstractions 0.9. It runs every kernel as a `KernelAbstractions.CPU()` kernel over plain `Array`s and has no +`synchronize`, so the harness skips that call. Code that would not compile for a GPU, such as a registered function +that allocates, passes on both. `JLSparseMatrixCSC` fails with scalar indexing, while a `GenericSparseMatrixCSC` with +JLArray storage works. + +## Vendor runs + +`vendor/amdgpu/` is not a declared group. Run it by hand on a machine with an AMD GPU, one GPU process at a time: + +```sh +julia --project=test/GPU/vendor/amdgpu -e 'using Pkg; Pkg.instantiate()' +julia --project=test/GPU/vendor/amdgpu test/GPU/vendor/amdgpu/runtests.jl +``` + +It runs the same kernels on `ROCBackend()`. It also checks that a registered function that allocates a `Dict` fails to +compile with an error that names it. + +| Backend | Status | +|---------|--------| +| `KernelAbstractions.CPU()`, JLArrays | supported: run in CI by the GPU group | +| AMDGPU | tested on Radeon 8060S (gfx1151), by hand | +| CUDA, oneAPI, Metal | untested | diff --git a/test/GPU/backends.jl b/test/GPU/backends.jl new file mode 100644 index 00000000..87517fa5 --- /dev/null +++ b/test/GPU/backends.jl @@ -0,0 +1,26 @@ +# Every prepared kernel of the real PDESystems in `common/cases.jl`, evaluated in a KernelAbstractions kernel on +# KernelAbstractions.CPU() and on JLArrays, equals the host Float64 kernel. Both run on the host: they test host-array +# discipline, not that a kernel compiles for a GPU (see README.md). +using JLArrays: JLArray, JLBackend +using GenericSparseArrays: GenericSparseMatrixCSC +using LinearAlgebra: mul! +using SparseArrays: sparse +include(joinpath(@__DIR__, "common", "backend.jl")) + +GPUArraysCore.allowscalar(false) + +@testset "KernelAbstractions.CPU()" begin + test_backend(KernelAbstractions.CPU(), identity) +end + +@testset "JLArrays" begin + test_backend(JLBackend(), JLArray) +end + +@testset "a GenericSparseMatrixCSC with JLArray storage multiplies a JLArray without scalar indexing" begin + A = sparse([1, 2, 3, 1], [1, 2, 3, 3], Float32[1, 2, 3, 4]) + G = GenericSparseMatrixCSC(size(A)..., JLArray(A.colptr), JLArray(A.rowval), JLArray(A.nzval)) + y = JLArray(zeros(Float32, 3)) + mul!(y, G, JLArray(ones(Float32, 3))) + @test Array(y) == A * ones(Float32, 3) +end diff --git a/test/GPU/common/backend.jl b/test/GPU/common/backend.jl new file mode 100644 index 00000000..0e835a33 --- /dev/null +++ b/test/GPU/common/backend.jl @@ -0,0 +1,26 @@ +# The end-to-end check of this layer on one backend: real PDESystem, emitted kernels, the device pass, a +# KernelAbstractions kernel, and its result against the host Float64 kernel. +using Test +# The four triggers of FiniteElementMethodKAExt. +using KernelAbstractions: KernelAbstractions +using Adapt: Adapt +using GPUArrays: GPUArrays +using GPUArraysCore: GPUArraysCore + +include(joinpath(@__DIR__, "cases.jl")) +include(joinpath(@__DIR__, "harness.jl")) + +# The largest relative error per precision over all kernels. +function test_backend(backend, toarr; rows = all_rows()) + pts, us = host_points() + worst = Dict(Float32 => 0.0, Float64 => 0.0) + @testset "$name/$role on $(nameof(typeof(backend)))" for (name, role, ex, g, sig, np) in rows + ref = reference(g, sig, np, pts, us) + for T in (Float32, Float64) + out = run_on(backend, toarr, FEM.device_kernel(ex, T), sig, np, pts, us, size(ref, 1), T) + worst[T] = max(worst[T], relerr(Float64.(out), ref)) + @test relerr(Float64.(out), ref) < rtol(T) + end + end + return worst +end diff --git a/test/GPU/common/cases.jl b/test/GPU/common/cases.jl new file mode 100644 index 00000000..88f85a24 --- /dev/null +++ b/test/GPU/common/cases.jl @@ -0,0 +1,111 @@ +# The kernels FEM emits for real PDESystems: each kernel as the `Expr` (`expression = Val(true)`) and as the host function +# `discretize` compiles, for the device-pass tests on every backend. +import FiniteElementMethod as FEM +using FiniteElementMethod: FEMDiscretization, MeshDomain, boundarypiece, NormalDerivative, Galerkin, SUPG, CellCoeffs, + weak_form, emit_kernels, emit_dirichlet +using ModelingToolkit: ModelingToolkit, PDESystem, Differential, @parameters, @named, t_nounits as t +using DomainSets: Interval +using Ferrite: generate_grid, Triangle, Vec +using Symbolics: Symbolics, @variables, @register_symbolic + +# A registered function GPU code can compile, and one that allocates a Dict, which it cannot. +goodf(z) = 1 + z^2 / (1 + z^2) +@register_symbolic goodf(z) +function badf(z) + d = Dict{Int, Float64}() + d[1] = z + return d[1] + 1 +end +@register_symbolic badf(z) + +@variables x y u(..) +@parameters k a +Dx, Dy, Dt = Differential(x), Differential(y), Differential(t) +U = u(t, x, y) +const Ω = MeshDomain(generate_grid(Triangle, (2, 2), Vec(0.0, 0.0), Vec(1.0, 1.0))) +const LEFT, RIGHT, TOP = boundarypiece.(Ω, (:left, :right, :top)) + +# The analysis `discretize` makes of `pdesys` (the front of `FiniteElementMethod._lower`), and its weak form. +function analysis(pdesys, disc) + PDEBase = FEM.PDEBase + sys, replaced = PDEBase.make_pdesys_compatible(pdesys) + v = PDEBase.VariableMap(sys, disc; replaced_vars = replaced) + PDEBase.interface_errors(sys, v, disc) + boundarymap = FEM._boundary_map(sys.bcs, v, disc) + ctx = FEM.StrongForm.SlotContext(sys, v) + an = FEM._paired(FEM.StrongForm.analyse(sys, v, boundarymap; ibp = disc.ibp), pdesys.eqs, ctx, disc) + return an, weak_form(an; test_space = disc.test_space) +end + +function system(eq, bcs; params = []) + @named pdesys = PDESystem([eq], [bcs; u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], params) + return pdesys +end + +# Mass, bilinear and source coefficients with a parameter, and a Neumann condition (a facet kernel). +heat() = system( + Dt(U) ~ Dx((1 + x^2 + y + k * sin(x)) * Dx(U)) + Dy((1 + x^2 + y + k * sin(x)) * Dy(U)) + x * y + 1, + [u(t, LEFT) ~ 0.1 * y, NormalDerivative(RIGHT)(u(t, RIGHT)) ~ 0.5]; params = [k => 0.3] +) +# SUPG: `CellCoeffs` with the element size hK. +advection() = system(Dt(U) ~ 0.01 * (Dx(Dx(U)) + Dy(Dy(U))) - Dx(U) - 0.5 * Dy(U) + 1, [u(t, LEFT) ~ 0, u(t, RIGHT) ~ 1]) +# A nonlinear diffusion and advection term: `f` and `tangent`. +nonlinear() = system( + Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) - U * Dx(U) + exp(x) * sin(y) / 2, + [u(t, LEFT) ~ sin(y) / 2] +) +# `NaNMath.pow` for a constant non-integer and a symbolic exponent, and NaNMath's log and sqrt. +powers() = system( + Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + (1 + x^2)^1.5 + (2 + y)^a + log(2 + x) + sqrt(1 + y) + t^0.25, + [u(t, LEFT) ~ 0]; params = [a => 0.7] +) +# Time-dependent Dirichlet data with a fractional power. +dirichlet() = system( + Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)), [u(t, LEFT) ~ sin(t) * (1 + y)^0.5 + k * y, u(t, TOP) ~ 2.0 * t]; + params = [k => 0.3] +) +registered(fn) = system(Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + fn(x + y), [u(t, LEFT) ~ 0]) + +const CASES = [ + "heat" => (heat, Galerkin()), + "supg" => (advection, SUPG((hK, b) -> hK / (2 * sqrt(b[1]^2 + b[2]^2)))), + "nonlinear" => (nonlinear, Galerkin()), + "powers" => (powers, Galerkin()), + "dirichlet" => (dirichlet, Galerkin()), + "goodf" => (() -> registered(goodf), Galerkin()), +] + +# One `(role, Expr, host function, signature)` per kernel function of `pdesys`. Signatures: `:coeffs` is +# `(X, T, N, P)`, `:cell` adds `hK`, `:full` is `(U, G, Ud, V, W, X, T, N, P)` and `:dirichlet` is `(X, T, P)`. +function kernel_rows(pdesys, test_space) + disc = FEMDiscretization(Ω, t; test_space) + an, wf = analysis(pdesys, disc) + rows = Tuple{String, Expr, Any, Symbol}[] + for (e, f) in zip(emit_kernels(wf; expression = Val(true)), emit_kernels(wf)) + tag = string(e.kind, e.piece === nothing ? "" : "@" * string(e.piece.name)) + if e.coeffs isa CellCoeffs + push!(rows, (tag * ".cellcoeffs", e.coeffs.f, f.coeffs.f, :cell)) + elseif e.coeffs !== nothing + push!(rows, (tag * ".coeffs", e.coeffs, f.coeffs, :coeffs)) + end + e.f === nothing || push!(rows, (tag * ".f", e.f, f.f, :full)) + e.tangent === nothing || push!(rows, (tag * ".tangent", e.tangent, f.tangent, :full)) + end + # `emit_dirichlet` has no `expression` keyword; this is its body. + s = an.slots + for (i, (bc, (_, _, g))) in enumerate(zip(an.essential, emit_dirichlet(an))) + ex = FEM.compile(FEM.assert_differentiated(bc.g), (s.X, s.T, s.P); expression = Val(true)) + push!(rows, ("dirichlet$i", ex, g, :dirichlet)) + end + return rows, length(s.P) +end + +# Every `(case, role, Expr, host function, signature, number of parameters)` of `CASES`. +function all_rows(cases = CASES) + out = [] + for (name, (pdesys, test_space)) in cases + rows, np = kernel_rows(pdesys(), test_space) + append!(out, [(name, role, ex, g, sig, np) for (role, ex, g, sig) in rows]) + end + return out +end diff --git a/test/GPU/common/harness.jl b/test/GPU/common/harness.jl new file mode 100644 index 00000000..f955fcf0 --- /dev/null +++ b/test/GPU/common/harness.jl @@ -0,0 +1,72 @@ +# A KernelAbstractions kernel that evaluates one generated kernel per point with driver-shaped arguments, and the +# comparison of a backend's result with the host Float64 kernel. +using FiniteElementMethod: StructuralZero +using Ferrite: Vec +using KernelAbstractions: KernelAbstractions, @kernel, @index, @Const +using Random: Random + +const NPTS = 256 + +vec2(::Type{T}, a, b) where {T} = Vec{2, T}((T(a), T(b))) + +# The arguments of a signature other than X and u, in precision T, with the `np` parameters as an NTuple. +function fixed_args(sig, ::Type{T}, np) where {T} + P = ntuple(i -> T(0.5 + 0.1i), np) + t, N = T(0.3), vec2(T, 0.6, 0.8) + sig === :coeffs && return (t, N, P) + sig === :cell && return (t, N, P, T(0.05)) + sig === :dirichlet && return (t, P) + return ((T(0.2), T(-0.4)), (T(0.7),), T(0.9), vec2(T, 0.3, -0.5), t, N, P) # G, Ud, V, W, T, N, P +end +callk(f, ::Val{:full}, X, u, (G, Ud, V, W, t, N, P)) = f((u,), G, Ud, V, W, X, t, N, P) +callk(f, ::Val, X, u, fixed) = f(X, fixed...) + +num(::StructuralZero, ::Type{T}) where {T} = zero(T) +num(x, ::Type{T}) where {T} = T(x) +@inline function store!(out, i, r::Tuple) + vals = map(v -> num(v, eltype(out)), r) + for j in 1:length(vals) + @inbounds out[j, i] = vals[j] + end + return nothing +end +@inline store!(out, i, r) = (@inbounds out[1, i] = num(r, eltype(out)); nothing) + +@kernel function eval_kernel!(out, f, @Const(pts), @Const(us), fixed, sig) + i = @index(Global) + X = Vec{2, eltype(out)}((pts[1, i], pts[2, i])) + store!(out, i, callk(f, sig, X, us[i], fixed)) +end + +nout(r::Tuple) = length(r) +nout(r) = 1 + +# Points in (0.1, 1.1)^2, so fractional powers, log and sqrt of the coordinates stay real; u in (0.5, 1.5). +host_points() = (Random.seed!(1); (0.1 .+ rand(2, NPTS), 0.5 .+ rand(NPTS))) + +# The kernel `g` evaluated pointwise on the host in precision T. +function reference(g, sig, np, pts, us, ::Type{T} = Float64) where {T} + fixed = fixed_args(sig, T, np) + at(i) = callk(g, Val(sig), vec2(T, pts[1, i], pts[2, i]), T(us[i]), fixed) + out = zeros(T, nout(at(1)), NPTS) + foreach(i -> store!(out, i, at(i)), 1:NPTS) + return out +end + +# JLArrays 0.3.3 (the last release for KernelAbstractions 0.9) defines no `synchronize(::JLBackend)`; its launches are +# synchronous. +sync(b) = hasmethod(KernelAbstractions.synchronize, Tuple{typeof(b)}) ? KernelAbstractions.synchronize(b) : nothing + +# The device kernel `dk` evaluated on `backend`, with arrays moved there by `toarr`; the output copied to the host. +function run_on(backend, toarr, dk, sig, np, pts, us, nrows, ::Type{T}) where {T} + out = KernelAbstractions.zeros(backend, T, nrows, NPTS) + eval_kernel!(backend, 64)(out, dk, toarr(T.(pts)), toarr(T.(us)), fixed_args(sig, T, np), Val(sig); ndrange = NPTS) + sync(backend) + return Array(out) +end + +relerr(a, b) = maximum(abs.(a .- b)) / max(maximum(abs.(b)), eps()) + +# Tolerances against the host Float64 kernel: Float32 kernels measured within 5.5e-7 on Radeon 8060S. +rtol(::Type{Float32}) = 1.0e-6 +rtol(::Type{Float64}) = 1.0e-13 diff --git a/test/GPU/devicepass.jl b/test/GPU/devicepass.jl new file mode 100644 index 00000000..00ec35c5 --- /dev/null +++ b/test/GPU/devicepass.jl @@ -0,0 +1,82 @@ +# The device pass on the host: the kernels of real PDESystems lose their Float64 literals and NaNMath.pow, compile to +# isbits functions, and in Float32 compute in Float32 to within 1e-6 of the Float64 kernels. Unsupported calls are +# refused when the kernel is prepared, and user functions are named when a kernel fails to compile. +using NaNMath: NaNMath +using RuntimeGeneratedFunctions: drop_expr +include(joinpath(@__DIR__, "common", "backend.jl")) + +const Ext = Base.get_extension(FEM, :FiniteElementMethodKAExt) +const ROWS = all_rows() +kernel(body) = Expr(:function, :((x, T)), Expr(:block, body)) +eltypes(r::Tuple) = Set(typeof.(r)) +eltypes(r) = Set([typeof(r)]) + +@testset "the extension loads with KernelAbstractions, Adapt, GPUArrays and GPUArraysCore" begin + @test Ext isa Module +end + +@testset "the raw kernels hold Float64 literals and NaNMath.pow, and promote Float32 arguments to Float64" begin + before = [Ext.device_violations(ex, Float32) for (_, _, ex) in ROWS] + @test any(v -> any(startswith("the Float64 literal"), v), before) + @test any(v -> any(startswith("NaNMath.pow"), v), before) + promoted = map(ROWS) do (_, _, _, g, sig, np) + Float64 in eltypes(callk(drop_expr(g), Val(sig), vec2(Float32, 0.4, 0.6), 0.8f0, fixed_args(sig, Float32, np))) + end + @test count(promoted) > length(ROWS) ÷ 2 +end + +@testset "after the pass $name/$role passes the device check, is isbits and computes in Float32" for (name, role, ex, g, sig, np) in ROWS + @test isempty(Ext.device_violations(Ext.retype(ex, Float32), Float32)) + @test isempty(Ext.device_violations(Ext.retype(ex, Float64), Float64)) + dk = FEM.device_kernel(ex, Float32) + @test isbits(dk) + @test Float64 ∉ eltypes(callk(dk, Val(sig), vec2(Float32, 0.4, 0.6), 0.8f0, fixed_args(sig, Float32, np))) + pts, us = host_points() + @test relerr(Float64.(reference(dk, sig, np, pts, us, Float32)), reference(g, sig, np, pts, us)) < rtol(Float32) +end + +@testset "prepared coefficient kernels in a LinearBlock are isbits; a KernelSpec is not" begin + rows = Dict(role => ex for (name, role, ex) in ROWS if name == "heat") + coeffs(kind) = FEM.device_kernel(rows["$kind.coeffs"], Float32) + @test isbits(FEM.LinearBlock(1, coeffs(:mass), coeffs(:bilinear), coeffs(:source))) + @test !isbits(FEM.KernelSpec(1, :source, nothing, nothing, nothing, coeffs(:source))) +end + +@testset "NaNMath.pow becomes nanpow: NaN for a negative base, where ^ throws a DomainError on the host" begin + @test_throws DomainError (-1.0f0)^1.5f0 + @test Ext.nanpow(-1.0f0, 1.5f0) isa Float32 && isnan(Ext.nanpow(-1.0f0, 1.5f0)) + for (b, e) in ((-1.0, 1.5), (-2.0, 2.0), (-2.0, 3), (2, 0.5), (3.0f0, 2), (2.0f0, 1.5f0)) + @test isequal(Ext.nanpow(b, e), NaNMath.pow(b, e)) + end + # The exponent here is the kernel's argument named T, which the pass must leave alone. + for pow in (NaNMath.pow, GlobalRef(NaNMath, :pow)) + dk = FEM.device_kernel(kernel(Expr(:call, pow, :x, :T)), Float32) + @test dk(3.0f0, 2.0f0) === 9.0f0 + @test isnan(FEM.device_kernel(kernel(Expr(:call, pow, :x, 1.5)), Float32)(-1.0f0, 0.0f0)) + end + @test FEM.device_kernel(kernel(:(x * -1 // 2 + 0.25)), Float32)(1.0f0, 0.0f0) === -0.25f0 +end + +@testset "library ccalls, closures and ccalls are refused when the kernel is prepared" begin + msg = "a generated kernel cannot run on a device: it contains NaNMath.lgamma, a library ccall with no device implementation" + @test_throws msg FEM.device_kernel(kernel(Expr(:call, NaNMath.lgamma, :x)), Float32) + @test_throws msg FEM.device_kernel(kernel(Expr(:call, GlobalRef(NaNMath, :lgamma), :x)), Float64) + @test_throws "it contains a closure" FEM.device_kernel(kernel(:(map(z -> z + 1, x))), Float32) + @test_throws "it contains a ccall" FEM.device_kernel(kernel(:(ccall(:sin, Float64, (Float64,), x))), Float32) + @test_throws "must be a floating-point type, got Int64" FEM.device_kernel(kernel(:x), Int) +end + +@testset "user-registered functions are listed, and named when a kernel fails to compile" begin + callees = unique(reduce(vcat, [Ext.foreign_callees(ex) for (_, ex) in first(kernel_rows(registered(badf), Galerkin()))])) + @test length(callees) == 1 && endswith(only(callees), ".badf") + # FEM's own calls (Base, NaNMath, StructuralZero) are never listed. + listed = unique(reduce(vcat, [Ext.foreign_callees(ex) for (_, _, ex) in ROWS])) + @test length(listed) == 1 && endswith(only(listed), ".goodf") + err = ErrorException("InvalidIRError: unsupported call to an unknown function") + cpu = KernelAbstractions.CPU() + msg = "a generated kernel failed to compile for CPU; it calls the user functions $(only(callees)), which must be " * + "GPU-compilable (no allocation, Dict, String or ccall). Original error: InvalidIRError: unsupported call" + @test_throws msg Ext.launch_checked(() -> throw(err), cpu, callees) + @test_throws err Ext.launch_checked(() -> throw(err), cpu, String[]) + @test Ext.launch_checked(() -> 1, cpu, callees) == 1 +end diff --git a/test/GPU/vendor/amdgpu/LocalPreferences.toml b/test/GPU/vendor/amdgpu/LocalPreferences.toml new file mode 100644 index 00000000..d3dd4178 --- /dev/null +++ b/test/GPU/vendor/amdgpu/LocalPreferences.toml @@ -0,0 +1,3 @@ +[AMDGPU] +soft_memory_limit = "6 GiB" +hard_memory_limit = "8 GiB" diff --git a/test/GPU/vendor/amdgpu/Project.toml b/test/GPU/vendor/amdgpu/Project.toml new file mode 100644 index 00000000..69e93124 --- /dev/null +++ b/test/GPU/vendor/amdgpu/Project.toml @@ -0,0 +1,41 @@ +[deps] +AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" +Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e" +DomainSets = "5b8099bc-c8ec-5219-889f-1d9e522a28bf" +Ferrite = "c061ca5d-56c9-439f-9c0e-210fe06d3992" +FiniteElementMethod = "e08948db-0ae8-498a-9b98-73fc7f237ce3" +GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7" +GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" +GenericSparseArrays = "da3fe0eb-88a8-4d14-ae1a-857c283e9c70" +JLArrays = "27aeb0d3-9eb9-45fb-866b-73c2ecf80fcb" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" +NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" +SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" +Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" + +[sources] +FiniteElementMethod = {path = "../../../.."} + +[compat] +AMDGPU = "2.8" +Adapt = "4" +DomainSets = "0.7, 0.8" +Ferrite = "1.7" +GPUArrays = "11" +GPUArraysCore = "0.2" +GenericSparseArrays = "0.1" +JLArrays = "0.3.3" +KernelAbstractions = "0.9" +LinearAlgebra = "1" +ModelingToolkit = "11" +NaNMath = "1.1.5" +Random = "1" +SafeTestsets = "0.1" +SparseArrays = "1" +Symbolics = "7" +Test = "1" diff --git a/test/GPU/vendor/amdgpu/runtests.jl b/test/GPU/vendor/amdgpu/runtests.jl new file mode 100644 index 00000000..16ac49a4 --- /dev/null +++ b/test/GPU/vendor/amdgpu/runtests.jl @@ -0,0 +1,37 @@ +# Run by hand on an AMD GPU, never in CI, and never alongside another GPU run: +# julia --project=test/GPU/vendor/amdgpu test/GPU/vendor/amdgpu/runtests.jl +# LocalPreferences.toml caps AMDGPU's pool at 6 GiB (soft) and 8 GiB (hard): the device memory is system RAM here. +using AMDGPU +include(joinpath(@__DIR__, "..", "..", "common", "backend.jl")) + +const Ext = Base.get_extension(FEM, :FiniteElementMethodKAExt) +AMDGPU.versioninfo() +println("KernelAbstractions ", pkgversion(KernelAbstractions), ", AMDGPU ", pkgversion(AMDGPU), ", device ", AMDGPU.device()) + +@testset "AMDGPU" begin + @test AMDGPU.functional() + backend = ROCBackend() + worst = test_backend(backend, ROCArray) + println("largest relative error against the host Float64 kernels: ", worst) + + @testset "a Dict-allocating registered function fails to compile, with an error naming it" begin + rows, np = kernel_rows(registered(badf), Galerkin()) + pts, us = host_points() + checked = 0 + for (role, ex, g, sig) in rows + callees = Ext.foreign_callees(ex) + isempty(callees) && continue + dk = FEM.device_kernel(ex, Float32) + nrows = size(reference(g, sig, np, pts, us), 1) + launch() = run_on(backend, ROCArray, dk, sig, np, pts, us, nrows, Float32) + @test_throws "a generated kernel failed to compile for ROCBackend; it calls the user functions $(only(callees))" Ext.launch_checked(launch, backend, callees) + try + Ext.launch_checked(launch, backend, callees) + catch err + println(role, ": ", sprint(showerror, err)) + end + checked += 1 + end + @test checked > 0 + end +end diff --git a/test/test_groups.toml b/test/test_groups.toml index 73ee2aaf..68664b67 100644 --- a/test/test_groups.toml +++ b/test/test_groups.toml @@ -46,5 +46,10 @@ versions = ["lts", "1"] in_all = false versions = ["lts", "1"] +# Device kernels on KernelAbstractions.CPU() and JLArrays; Julia 1 only, for the `[sources]` path in test/GPU. +[GPU] +in_all = false +versions = ["1"] + [NavierStokes] versions = ["lts", "1", "pre"]