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
6 changes: 6 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,23 @@ SymbolicUtils = "d1185830-fcd6-423d-90d6-eec64667417b"
Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7"

[weakdeps]
AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e"
Adapt = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
FerriteGmsh = "4f95f4f8-b27c-4ae5-9a39-ea55e634e36b"
GPUArrays = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
GenericSparseArrays = "da3fe0eb-88a8-4d14-ae1a-857c283e9c70"
KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c"

[extensions]
FiniteElementMethodAMDGPUExt = ["AMDGPU", "KernelAbstractions", "Adapt", "GPUArrays", "GPUArraysCore"]
FiniteElementMethodFerriteGmshExt = "FerriteGmsh"
FiniteElementMethodGenericSparseArraysExt = ["GenericSparseArrays", "KernelAbstractions", "Adapt", "GPUArrays", "GPUArraysCore"]
FiniteElementMethodKAExt = ["KernelAbstractions", "Adapt", "GPUArrays", "GPUArraysCore"]

[compat]
ADTypes = "1.24"
AMDGPU = "2"
Adapt = "4"
AllocCheck = "0.2"
DiffEqBase = "7.21"
Expand All @@ -42,6 +47,7 @@ FerriteGmsh = "1.5"
ForwardDiff = "1.4"
GPUArrays = "11"
GPUArraysCore = "0.2"
GenericSparseArrays = "0.1"
Gmsh = "0.3"
KernelAbstractions = "0.9"
LinearAlgebra = "1.10"
Expand Down
11 changes: 11 additions & 0 deletions ext/FiniteElementMethodAMDGPUExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module FiniteElementMethodAMDGPUExt

# The AMDGPU specifics of device assembly; the assembly itself is backend-neutral, in FiniteElementMethodKAExt.
using FiniteElementMethod: FiniteElementMethod as FEM
using AMDGPU: ROCBackend
using AMDGPU.rocSPARSE: ROCSparseMatrixCSC

FEM.device_matrix_type(::ROCBackend, Tv, Ti) = ROCSparseMatrixCSC{Tv, Ti}
FEM.supports_float64(::ROCBackend) = true

end # module
18 changes: 18 additions & 0 deletions ext/FiniteElementMethodGenericSparseArraysExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module FiniteElementMethodGenericSparseArraysExt

# The sparse matrix of backends without a sparse matrix library of their own (JLArrays here; Metal in Ferrite): a
# GenericSparseMatrixCSC whose storage vectors live on the backend. Vendor extensions name more specific types.
using FiniteElementMethod: FiniteElementMethod as FEM
using Adapt: adapt
using GenericSparseArrays: GenericSparseMatrixCSC
using KernelAbstractions: KernelAbstractions as KA
using SparseArrays: SparseArrays, SparseMatrixCSC, nonzeros, rowvals

FEM.device_matrix_type(::KA.GPU, Tv, Ti) = GenericSparseMatrixCSC{Tv, Ti}

function FEM.device_matrix(::Type{<:GenericSparseMatrixCSC{Tv, Ti}}, backend, A) where {Tv, Ti}
storage(v, S) = adapt(backend, Vector{S}(v))
return GenericSparseMatrixCSC(size(A)..., storage(SparseArrays.getcolptr(A), Ti), storage(rowvals(A), Ti), storage(nonzeros(A), Tv))
end

end # module
11 changes: 9 additions & 2 deletions ext/FiniteElementMethodKAExt.jl
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
module FiniteElementMethodKAExt

using FiniteElementMethod: FiniteElementMethod
using KernelAbstractions: KernelAbstractions
using RuntimeGeneratedFunctions: RuntimeGeneratedFunction, drop_expr
const FEM = FiniteElementMethod
using Adapt: adapt
using Ferrite: Ferrite
using KernelAbstractions: KernelAbstractions, @kernel, @index, @Const, @ndrange
const KA = KernelAbstractions
using RuntimeGeneratedFunctions: RuntimeGeneratedFunctions, RuntimeGeneratedFunction, drop_expr
using SparseArrays: SparseArrays, SparseMatrixCSC, nonzeros, rowvals

# NaNMath is not a dependency, so its functions are recognised by module and function name.
callee(f::Function) = (parentmodule(f), nameof(f))
Expand Down Expand Up @@ -105,4 +110,6 @@ function launch_checked(launch, backend::KernelAbstractions.Backend, callees)
end
end

include("FiniteElementMethodKAExt/assembly.jl")

end # module
180 changes: 180 additions & 0 deletions ext/FiniteElementMethodKAExt/assembly.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# Device assembly of the linear operators M, K and F (`FEMDiscretization(...; backend)`): the cells of each
# SubDofHandler are scattered by KernelAbstractions kernels that call the host driver's element routine on per-worker
# element buffers, and the result is copied back into the host operators.

FEM.is_device_backend(::KA.Backend) = true
FEM.supports_float64(::KA.Backend) = true
FEM.device_matrix_type(::KA.CPU, Tv, Ti) = SparseMatrixCSC{Tv, Ti}
FEM.device_matrix_type(backend::KA.Backend, Tv, Ti) = throw(
ArgumentError(
"no device sparse matrix type is known for $(nameof(typeof(backend))): load its vendor package " *
"(AMDGPU for ROCBackend()), or GenericSparseArrays for a backend without a sparse matrix library"
)
)

function check_ferrite_gpu(ext)
ext === nothing && throw(
ArgumentError(
"device assembly needs a Ferrite with GPU support (the FerriteKAExt extension, Ferrite.jl PR #1496); " *
"the loaded Ferrite $(pkgversion(Ferrite)) has none"
)
)
return nothing
end

function working_precision(backend, precision)
T = something(precision, Float64)
T === Float64 && !FEM.supports_float64(backend) &&
throw(ArgumentError("$(nameof(typeof(backend))) has no Float64; pass precision = Float32"))
return T
end

# Workers per launch and the workgroup size. On the CPU a workgroup runs on one thread, so a worker is a workgroup.
launch_shape(::KA.CPU) = (; workers = 4 * Threads.nthreads(), groupsize = 1)
launch_shape(::KA.Backend) = (; workers = 2^14, groupsize = 64)

# A device matrix with the stored entries of `A`, so the copy back needs only the values. Vendor matrix types are
# built from device storage vectors, as Ferrite's `allocate_matrix` builds them.
FEM.device_matrix(::Type{SparseMatrixCSC{Tv, Ti}}, backend, A) where {Tv, Ti} = SparseMatrixCSC{Tv, Ti}(A)
function FEM.device_matrix(::Type{MT}, backend, A) where {MT}
Tv, Ti = eltype(MT), eltype(rowvals(A))
storage(v, S) = adapt(backend, Vector{S}(v))
return MT(storage(SparseArrays.getcolptr(A), Ti), storage(rowvals(A), Ti), storage(nonzeros(A), Tv), size(A))
end

device_fn(::Nothing, T) = nothing
device_fn(f::RuntimeGeneratedFunction, T) = FEM.device_kernel(RuntimeGeneratedFunctions.get_expression(f), T)
device_fn(c::FEM.CellCoeffs, T) = FEM.CellCoeffs(device_fn(c.f, T), c.fields)
function device_block(b::FEM.LinearBlock, T)
return FEM.LinearBlock(b.eq, device_fn(b.mass, T), device_fn(b.bilinear, T), device_fn(b.source, T))
end
device_block(k, T) = throw(
ArgumentError("device assembly needs the coefficient form of every linear kernel, but the $(k.kind) kernel of equation $(k.eq) has none")
)

host_fns(b::FEM.LinearBlock) = filter(!isnothing, [b.mass, b.bilinear, b.source])
host_expr(f::RuntimeGeneratedFunction) = RuntimeGeneratedFunctions.get_expression(f)
host_expr(c::FEM.CellCoeffs) = host_expr(c.f)

function quadrature_in(::Type{T}, qr::Ferrite.QuadratureRule{shape}) where {T, shape}
return Ferrite.QuadratureRule{shape}(T.(Ferrite.getweights(qr)), map(x -> Ferrite.Vec{length(x), T}(Tuple(x)), Ferrite.getpoints(qr)))
end
function cellvalues_in(::Type{T}, cv) where {T}
qr = quadrature_in(T, Ferrite.get_quadrature_rule(cv))
return Ferrite.CellValues(T, qr, Ferrite.function_interpolation(cv), Ferrite.geometric_interpolation(cv))
end

# The DofHandler on a copy of the grid with coordinates in precision T, with the host dof numbering.
dofhandler_in(::Type{T}, dh::Ferrite.DofHandler{dim, <:Ferrite.Grid{dim, <:Any, T}}) where {T, dim} = dh
function dofhandler_in(::Type{T}, dh::Ferrite.DofHandler{dim}) where {T, dim}
nodes = [Ferrite.Node(Ferrite.Vec{dim, T}(Tuple(Ferrite.get_node_coordinate(n)))) for n in Ferrite.getnodes(dh.grid)]
dhT = Ferrite.DofHandler(Ferrite.Grid(Ferrite.getcells(dh.grid), nodes))
for sdh in dh.subdofhandlers
sub = Ferrite.SubDofHandler(dhT, sdh.cellset)
foreach((name, ip) -> Ferrite.add!(sub, name, ip), sdh.field_names, sdh.field_interpolations)
end
Ferrite.close!(dhT)
dhT.cell_dofs_offset == dh.cell_dofs_offset && length(dhT.cell_dofs) == length(dh.cell_dofs) ||
error("the DofHandler rebuilt in $T has a different layout from the host DofHandler")
copyto!(dhT.cell_dofs, dh.cell_dofs)
return dhT
end

# One SubDofHandler on the device: its dof range per field, the cells of each launch (one per color, or all cells
# for atomic assembly), and per worker a CellCache, the CellValues of every field and the element buffers.
struct DeviceSubdomain{R, L, CC, CV, A3, A2}
ranges::R
launches::L
cells::CC
values::CV
Me::A3
Ke::A3
Fe::A2
end

struct DeviceAssemblyContext{B, S}
backend::B
subdomains::S
atomic::Bool
end

function DeviceAssemblyContext(backend, ctx::FEM.AssemblyContext{NF}, ::Type{T}; atomic = false) where {NF, T}
dh = dofhandler_in(T, ctx.dh)
device_dh = adapt(backend, dh)
values = map(cv -> cellvalues_in(T, cv), Tuple(ctx.cellvalues))
shape = launch_shape(backend)
subdomains = map(enumerate(ctx.dh.subdofhandlers)) do (i, sdh)
ranges = ntuple(f -> FEM._field_range(sdh, ctx.fields[f]), Val(NF))
groups = atomic ? [collect(Int, sdh.cellset)] : Ferrite.create_coloring(ctx.dh.grid, sdh.cellset)
nw = min(maximum(length, groups), shape.workers)
ne = Ferrite.ndofs_per_cell(sdh)
DeviceSubdomain(
ranges, [adapt(backend, g) for g in groups],
Ferrite.distribute_to_workers(backend, Ferrite.CellCache(device_dh.subdofhandlers[i]), nw),
map(cv -> Ferrite.distribute_to_workers(backend, cv, nw), values),
KA.zeros(backend, T, nw, ne, ne), KA.zeros(backend, T, nw, ne, ne), KA.zeros(backend, T, nw, ne)
)
end
return DeviceAssemblyContext(backend, Tuple(subdomains), atomic)
end

workers(s::DeviceSubdomain) = size(s.Me, 1)

@kernel function linear_cells!(aM, aK, @Const(cellids), cells, values, Mes, Kes, Fes, kernels, ranges, p, t)
w = @index(Global, Linear)
stride = prod(@ndrange())
cc, vals = cells[w], map(v -> v[w], values)
am, ak = aM[w], aK[w]
Me, Ke, Fe = view(Mes, w, :, :), view(Kes, w, :, :), view(Fes, w, :)
op = FEM.LinearOp(nothing, nothing, Fe, Me, Ke, Fe)
for task in w:stride:length(cellids)
Ferrite.reinit!(cc, cellids[task])
FEM._reinit_all!(vals, cc)
fill!(Me, 0)
fill!(Ke, 0)
fill!(Fe, 0)
FEM._kernels!(op, kernels, vals, Ferrite.getcoordinates(cc), ranges, p, t)
dofs = Ferrite.celldofs(cc)
Ferrite.assemble!(ak, dofs, Ke, Fe)
Ferrite.assemble!(am, dofs, Me)
end
end

# JLArrays 0.3.3, the last release for KernelAbstractions 0.9, defines no `synchronize`; its launches are synchronous.
sync(backend) = hasmethod(KA.synchronize, Tuple{typeof(backend)}) ? KA.synchronize(backend) : nothing

# Adds the device `kernels` (`LinearBlock`s of prepared functions) into `Md`, `Kd` and `Fd`.
function assemble_device!(Md, Kd, Fd, dctx::DeviceAssemblyContext, kernels, p, t; callees = String[])
backend = dctx.backend
for s in dctx.subdomains
nw = workers(s)
aM = Ferrite.distribute_to_workers(backend, Ferrite.start_assemble(Md; fillzero = false, atomic = dctx.atomic), nw)
aK = Ferrite.distribute_to_workers(backend, Ferrite.start_assemble(Kd, Fd; fillzero = false, atomic = dctx.atomic), nw)
kernel! = linear_cells!(backend, launch_shape(backend).groupsize)
for cellids in s.launches
launch() = kernel!(aM, aK, cellids, s.cells, s.values, s.Me, s.Ke, s.Fe, kernels, s.ranges, p, t; ndrange = min(length(cellids), nw))
launch_checked(launch, backend, callees)
sync(backend)
end
end
return Md, Kd, Fd
end

function FEM.device_assemble_linear!(backend::KA.Backend, precision, assembly, M, K, F, ctx::FEM.AssemblyContext, kernels, p, t)
check_ferrite_gpu(Base.get_extension(Ferrite, :FerriteKAExt))
T = working_precision(backend, precision)
volume, groups = FEM._split(ctx, kernels, FEM.LINEAR_KINDS)
isempty(groups) || throw(ArgumentError("device assembly does not support facet kernels yet"))
dkernels = map(k -> device_block(k, T), volume)
callees = sort!(unique!(reduce(vcat, [foreign_callees(host_expr(f)) for b in volume for f in host_fns(b)]; init = String[])))
dctx = DeviceAssemblyContext(backend, ctx, T; atomic = assembly === :atomic)
MT = FEM.device_matrix_type(backend, T, eltype(rowvals(K)))
zero_pattern = SparseMatrixCSC(size(K)..., SparseArrays.getcolptr(K), rowvals(K), zeros(T, length(nonzeros(K))))
Md, Kd = FEM.device_matrix(MT, backend, zero_pattern), FEM.device_matrix(MT, backend, zero_pattern)
Fd = KA.zeros(backend, T, length(F))
assemble_device!(Md, Kd, Fd, dctx, dkernels, Tuple(T.(p)), T(t); callees)
nonzeros(M) .= Array(nonzeros(Md))
nonzeros(K) .= Array(nonzeros(Kd))
F .= Array(Fd)
return M, K, F
end
19 changes: 19 additions & 0 deletions src/assembly.jl
Original file line number Diff line number Diff line change
Expand Up @@ -597,3 +597,22 @@ end
end
return nothing
end

# Device assembly (`FEMDiscretization(...; backend)`). The methods for KernelAbstractions backends are in
# FiniteElementMethodKAExt; the vendor extensions add `device_matrix_type` and `supports_float64` for their backends.
is_device_backend(_) = false
function device_matrix_type end
function device_matrix end
function supports_float64 end
device_assemble_linear!(backend, args...) = throw(backend_error(backend))

function backend_error(backend)
Base.get_extension(@__MODULE__, :FiniteElementMethodKAExt) === nothing || return ArgumentError(
"backend must be a KernelAbstractions.Backend, such as ROCBackend() or KernelAbstractions.CPU(), or nothing; got $(repr(backend))"
)
return ArgumentError(
"backend = $(repr(backend)) needs the KernelAbstractions extension of FiniteElementMethod: load " *
"KernelAbstractions, Adapt, GPUArrays and GPUArraysCore, and the vendor package (AMDGPU for ROCBackend()), " *
"with a Ferrite that has GPU support (Ferrite.jl PR #1496)"
)
end
39 changes: 36 additions & 3 deletions src/discretization.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ PDEBase.contains_point(grid::Ferrite.Grid, x) = _contains_point(grid, x)
"""
FEMDiscretization(Ω::MeshDomain, t = nothing; spaces = Dict(), regions = Dict(),
quadrature = nothing, test_space = Galerkin(), ibp = Dict(), pairing = Dict(),
codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check = :warn, kwargs...)
codegen = :numeric, dirichlet = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check = :warn,
backend = nothing, precision = nothing, assembly = :colored, kwargs...)

Finite-element discretization of a `PDESystem` whose spatial domain is the mesh domain `Ω`
(of a `Ferrite.Grid`), with time variable `t`. `discretize(pdesys, disc)` assembles the
Expand Down Expand Up @@ -74,6 +75,27 @@ gives a `PDENoTimeSolution`.
still returns full fields, with `g` at the prescribed nodes, through `sol[u]`,
`sol(t, x, y)`, traces and `write_vtk`; only `sol.original_sol` and the array unknowns
hold the free dofs alone. `:algebraic` is recommended.
- `backend`: a KernelAbstractions backend, such as `ROCBackend()` or `KernelAbstractions.CPU()`, on
which the mass matrix, the stiffness matrix and the load are assembled; `nothing` (default)
assembles on the host. Only the assembly runs on the device: the operators are copied back as
`Float64` `SparseMatrixCSC`s, `discretize` returns the same host problem as without a backend,
and its solve runs on the host. It needs KernelAbstractions, Adapt, GPUArrays and GPUArraysCore
loaded (with the vendor package, e.g. AMDGPU for `ROCBackend()`, or GenericSparseArrays for a
backend without one) and a Ferrite with GPU support (Ferrite.jl PR #1496); otherwise the
constructor or `discretize` raises an `ArgumentError` saying what to load. Device assembly covers
volume terms of linear problems with sources constant in time and Dirichlet conditions (constant
or time-dependent, applied on the host); facet terms (Neumann and Robin conditions), nonlinear
terms, time-dependent sources, `SUPG` and `dirichlet = :eliminate` raise an `ArgumentError` naming
the feature. Generated kernels that call registered functions need those functions to be
GPU-compilable. `KernelAbstractions.CPU()` and JLArrays are tested in CI, AMDGPU is tested on a
Radeon 8060S (gfx1151), and CUDA, oneAPI and Metal are untested.
- `precision`: the floating-point type of device assembly, `Float32` or `Float64`; `nothing`
(default) is `Float64`. `Float32` operators agree with the host assembly to about `1e-6`
relative before they are converted to `Float64`. It needs a `backend`.
- `assembly`: how cells are scattered on the device. `:colored` (default) makes one launch per
color of cells that share no dof, so the result is deterministic; `:atomic` makes one launch
per `SubDofHandler` with atomic additions, whose summation order, and so the rounding, can vary
between runs.
- `codegen = :mtk` is reserved and raises; remaining keywords are
passed to the `DAEProblem` (or `NonlinearProblem`), where a keyword given at the
`discretize` call wins. `iv`, `unknowns`, `du0`, `coordinate`, `name` and `parameters` are set
Expand Down Expand Up @@ -110,6 +132,9 @@ struct FEMDiscretization{T} <: PDEBase.AbstractMeshDiscretization
natural::Vector{Symbol}
boundary_check::Symbol
algebraic_abstol::Union{Symbol, Nothing, Float64}
backend::Any
precision::Union{Nothing, DataType}
assembly::Symbol
kwargs::NamedTuple
end

Expand Down Expand Up @@ -142,7 +167,8 @@ end
function FEMDiscretization(
domain::PDEBase.MeshDomain, time = nothing; spaces = Dict(), regions = Dict(), quadrature = nothing,
test_space = Galerkin(), ibp = Dict(), pairing = Dict(), codegen::Symbol = :numeric,
dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check::Symbol = :warn, kwargs...
dirichlet::Symbol = :algebraic, algebraic_abstol = :auto, natural = (), boundary_check::Symbol = :warn,
backend = nothing, precision = nothing, assembly::Symbol = :colored, kwargs...
)
domain.mesh isa Ferrite.Grid ||
throw(ArgumentError("FEMDiscretization needs a MeshDomain of a Ferrite.Grid, got a mesh of type $(typeof(domain.mesh))"))
Expand All @@ -167,12 +193,19 @@ function FEMDiscretization(
"algebraic_abstol applies to time-dependent problems (the DAE path); a steady FEMDiscretization has no time stepper"
)
)
backend === nothing || is_device_backend(backend) || throw(backend_error(backend))
precision === nothing || precision in (Float32, Float64) ||
throw(ArgumentError("precision must be Float32, Float64 or nothing, got $(repr(precision))"))
precision !== nothing && backend === nothing &&
throw(ArgumentError("precision = $precision sets the precision of device assembly, so it needs a backend"))
assembly in (:colored, :atomic) || throw(ArgumentError("assembly must be :colored or :atomic, got $(repr(assembly))"))
_check_reserved(kwargs)
return FEMDiscretization{typeof(time)}(
domain, time, Dict{Any, Ferrite.Interpolation}(_field_op(k) => ip for (k, ip) in spaces),
Dict{Any, Any}(_field_op(k) => r for (k, r) in regions),
quadrature, test_space, Dict{Any, StrongForm.IBPPolicy}(ibp), Dict{Equation, Any}(pairing),
codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol, NamedTuple(kwargs)
codegen, dirichlet, unique(natural), boundary_check, algebraic_abstol isa Real ? Float64(algebraic_abstol) : algebraic_abstol,
backend, precision, assembly, NamedTuple(kwargs)
)
end

Expand Down
Loading
Loading