Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
108 changes: 108 additions & 0 deletions ext/FiniteElementMethodKAExt.jl
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions src/kernels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
)
41 changes: 41 additions & 0 deletions test/GPU/Project.toml
Original file line number Diff line number Diff line change
@@ -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"
51 changes: 51 additions & 0 deletions test/GPU/README.md
Original file line number Diff line number Diff line change
@@ -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 |
26 changes: 26 additions & 0 deletions test/GPU/backends.jl
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions test/GPU/common/backend.jl
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading