diff --git a/Project.toml b/Project.toml index 983642b0..a19c9e9e 100644 --- a/Project.toml +++ b/Project.toml @@ -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" @@ -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" diff --git a/ext/FiniteElementMethodAMDGPUExt.jl b/ext/FiniteElementMethodAMDGPUExt.jl new file mode 100644 index 00000000..517f6d06 --- /dev/null +++ b/ext/FiniteElementMethodAMDGPUExt.jl @@ -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 diff --git a/ext/FiniteElementMethodGenericSparseArraysExt.jl b/ext/FiniteElementMethodGenericSparseArraysExt.jl new file mode 100644 index 00000000..186e4778 --- /dev/null +++ b/ext/FiniteElementMethodGenericSparseArraysExt.jl @@ -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 diff --git a/ext/FiniteElementMethodKAExt.jl b/ext/FiniteElementMethodKAExt.jl index 160e9cb1..ca34db2d 100644 --- a/ext/FiniteElementMethodKAExt.jl +++ b/ext/FiniteElementMethodKAExt.jl @@ -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)) @@ -105,4 +110,6 @@ function launch_checked(launch, backend::KernelAbstractions.Backend, callees) end end +include("FiniteElementMethodKAExt/assembly.jl") + end # module diff --git a/ext/FiniteElementMethodKAExt/assembly.jl b/ext/FiniteElementMethodKAExt/assembly.jl new file mode 100644 index 00000000..7e7e94b0 --- /dev/null +++ b/ext/FiniteElementMethodKAExt/assembly.jl @@ -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 diff --git a/src/assembly.jl b/src/assembly.jl index 12e76d3d..5fc7411d 100644 --- a/src/assembly.jl +++ b/src/assembly.jl @@ -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 diff --git a/src/discretization.jl b/src/discretization.jl index 44a2260f..3a52a00f 100644 --- a/src/discretization.jl +++ b/src/discretization.jl @@ -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 @@ -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 @@ -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 @@ -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))")) @@ -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 diff --git a/src/frontend.jl b/src/frontend.jl index 6b2731d0..487bbe40 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -269,7 +269,7 @@ function assemble_sources!(F, ctx::AssemblyContext, kernels, p, t) return F end -function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) +function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet; backend = nothing, precision = nothing, assembly = :colored) kernels = emit_kernels(wf) # `emit_kernels` sums the terms sharing an equation, kind and piece, so a kernel is dynamic when any of its terms is. terms = [[(t, nothing) for t in wf.volume]; [(t, t.piece) for t in wf.facet]] @@ -281,7 +281,11 @@ function _operators(space, wf, names, dirichlet, pvals, t0, timedep_dirichlet) ctx = AssemblyContext(space.dh, space.fields, space.cellvalues, space.facetvalues, pieces) n = Ferrite.ndofs(space.dh) M, K, F = copy(space.pattern), copy(space.pattern), zeros(n) - assemble_linear!(M, K, F, ctx, static, pvals; t = t0) + if backend === nothing + assemble_linear!(M, K, F, ctx, static, pvals; t = t0) + else + device_assemble_linear!(backend, precision, assembly, M, K, F, ctx, static, pvals, t0) + end load = isempty(dynamic) ? F : (out, t) -> (assemble_sources!(out, _fresh_values(ctx), dynamic, pvals, t); out .+= F) nonlinear = any(k -> k.kind === :nonlinear, kernels) ? FEMNonlinear(NonlinearOperator(_fresh_values(ctx), kernels; ch = space.ch), pvals) : nothing @@ -359,6 +363,22 @@ function _check_boundary_conditions(disc::FEMDiscretization, an, ctx) return nothing end +# What device assembly (`backend`) does not cover yet; each is refused before anything is assembled. +function _check_device_scope(disc, wf) + unsupported(what) = throw( + ArgumentError( + "backend = $(disc.backend): device assembly does not support $what yet; " * + "remove the backend keyword to assemble on the host" + ) + ) + disc.dirichlet === :eliminate && unsupported("dirichlet = :eliminate (use the default dirichlet = :algebraic)") + disc.test_space isa SUPG && unsupported("the SUPG test space") + isempty(wf.facet) || unsupported("facet terms (Neumann and Robin conditions)") + any(t -> t.kind === :nonlinear, wf.volume) && unsupported("nonlinear terms") + any(t -> t.kind === :source && t.timedep, wf.volume) && unsupported("sources that depend on time") + return nothing +end + function _lower(pdesys, disc::FEMDiscretization) _check_domains(pdesys, disc) sys, replaced = PDEBase.make_pdesys_compatible(pdesys) @@ -388,7 +408,8 @@ function _lower(pdesys, disc::FEMDiscretization) "$(an.essential[timedep].piece.name) depends on time; use the default dirichlet = :algebraic" ) ) - ops, coords, raw = _operators(space, wf, names, dirichlet, pvals, t0, timedep !== nothing) + disc.backend === nothing || _check_device_scope(disc, wf) + ops, coords, raw = _operators(space, wf, names, dirichlet, pvals, t0, timedep !== nothing; disc.backend, disc.precision, disc.assembly) u0 = _initial_values(Equation[b.eq for b in ics], ctx, space, coords, an, names, pvals) dirichlet_values!(view(u0, ops.prescribed), ops.load, t0) elimination = nothing diff --git a/test/Frontend/backend.jl b/test/Frontend/backend.jl new file mode 100644 index 00000000..66db61ab --- /dev/null +++ b/test/Frontend/backend.jl @@ -0,0 +1,19 @@ +# Device assembly needs FiniteElementMethodKAExt, which this group never loads: a `backend` is refused at construction +# with what to load, and `backend = nothing` is the host path. Device assembly itself is tested in test/GPU. +using FiniteElementMethod, Test +using FiniteElementMethod: rectangle_grid +using Ferrite: Triangle +using ModelingToolkit: t_nounits as t + +Ω = MeshDomain(rectangle_grid(Triangle, (2, 2))) + +@testset "a backend without the KernelAbstractions extension raises what to load" begin + @test Base.get_extension(FiniteElementMethod, :FiniteElementMethodKAExt) === nothing + @test_throws "backend = :rocm 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)" FEMDiscretization(Ω, t; backend = :rocm) + @test_throws "backend = :rocm needs the KernelAbstractions extension" FiniteElementMethod.device_assemble_linear!(:rocm) +end + +@testset "the default backend = nothing assembles on the host" begin + disc = FEMDiscretization(Ω, t) + @test disc.backend === nothing && disc.precision === nothing && disc.assembly === :colored +end diff --git a/test/GPU/Project.toml b/test/GPU/Project.toml index 6aba3199..dd45838f 100644 --- a/test/GPU/Project.toml +++ b/test/GPU/Project.toml @@ -11,6 +11,7 @@ KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" RuntimeGeneratedFunctions = "7e49a35a-f44a-4d26-94aa-eba1b4ca6b47" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" @@ -19,6 +20,7 @@ Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [sources] +Ferrite = {url = "https://github.com/Ferrite-FEM/Ferrite.jl", rev = "do/gpu-ci"} FiniteElementMethod = {path = "../.."} [compat] @@ -33,6 +35,7 @@ KernelAbstractions = "0.9" LinearAlgebra = "1" ModelingToolkit = "11" NaNMath = "1.1.5" +OrdinaryDiffEqBDF = "2.4.1" Random = "1" RuntimeGeneratedFunctions = "0.5.12" SafeTestsets = "0.1" diff --git a/test/GPU/README.md b/test/GPU/README.md index e622ea8b..4b7dbef6 100644 --- a/test/GPU/README.md +++ b/test/GPU/README.md @@ -2,7 +2,9 @@ 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. +`Project.toml` develops the package through `[sources]`, which Julia 1.10 ignores. Device assembly needs Ferrite's +KernelAbstractions assembler, which no Ferrite release has yet: `[sources]` takes Ferrite from the branch of Ferrite.jl +PR #1496 (`do/gpu-ci`), while the package itself keeps `Ferrite = "1.7"`. ```sh GROUP=GPU julia --project=. -e 'using Pkg; Pkg.test()' @@ -14,13 +16,21 @@ The kernels come from real `PDESystem`s (`common/cases.jl`). They cover mass, bi 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. +kernel whose result must equal the host Float64 kernel. - `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. +- `assembly.jl` runs `discretize` with `backend` set on `KernelAbstractions.CPU()` and on JLArrays (`common/assembly.jl`): + a 3D P1 hexahedron and a 2D P2 triangle heat problem and a two-field problem of P2 and P1, each with constant and + time-dependent Dirichlet data, in Float32 and Float64, colored and atomic. M, K and F equal the host assembly within + 1e-5 relative in Float32 and 1e-12 in Float64, and the solution at a point equals the host solution. Colored + assembly is deterministic, and a steady problem assembled on the device solves to the host solution. +- `extension.jl` checks that FEM's and Ferrite's KernelAbstractions extensions are loaded, the validation of the + `backend`, `precision` and `assembly` keywords, the error for a Ferrite without GPU support, and the `ArgumentError` + for each feature device assembly does not cover yet. The error for a `backend` without the extension is tested in + `test/Frontend/backend.jl`, where the extension never loads. - `backends.jl` evaluates every prepared kernel in a `@kernel` on `KernelAbstractions.CPU()` and on JLArrays, in Float32 and Float64. @@ -41,7 +51,7 @@ 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 +It runs the same kernels and the device assembly cases of `common/assembly.jl` on `ROCBackend()`. It also checks that a registered function that allocates a `Dict` fails to compile with an error that names it. | Backend | Status | diff --git a/test/GPU/assembly.jl b/test/GPU/assembly.jl new file mode 100644 index 00000000..b5544bde --- /dev/null +++ b/test/GPU/assembly.jl @@ -0,0 +1,37 @@ +# Device assembly through `discretize` on KernelAbstractions.CPU() and JLArrays: the operators equal the host +# assembly and the problems solve to the host solution (`common/assembly.jl`). Both backends run on the host, so they +# test the portable code and host-array discipline, not that the kernels compile for a GPU (see README.md). +using JLArrays: JLBackend +using GenericSparseArrays: GenericSparseArrays +include(joinpath(@__DIR__, "common", "assembly.jl")) + +GPUArraysCore.allowscalar(false) + +@testset "KernelAbstractions.CPU()" begin + println("largest relative errors on KernelAbstractions.CPU(): ", test_device_assembly(KernelAbstractions.CPU())) +end + +@testset "JLArrays" begin + println("largest relative errors on JLArrays: ", test_device_assembly(JLBackend())) +end + +@testset "colored assembly gives the same operators on every run" begin + pdesys, Ω, spaces, _ = heat3d(CONSTANT_G) + disc = FEMDiscretization(Ω, t; spaces, boundary_check = :off, backend = JLBackend(), precision = Float32) + a, b = lowered(pdesys, disc), lowered(pdesys, disc) + @test a.M == b.M && a.K == b.K && a.F == b.F +end + +@testset "a steady problem assembled on the device solves to the host solution" begin + Ω = MeshDomain(generate_grid(Triangle, (4, 4), Vec(0.0, 0.0), Vec(1.0, 1.0))) + U = u(x, y) + @named pdesys = PDESystem( + [0 ~ Dx(Dx(U)) + Dy(Dy(U)) + 1 + x], [u(boundarypiece(Ω, :left)) ~ 0, u(boundarypiece(Ω, :right)) ~ y], + [(x, y) ∈ Ω], [x, y], [U] + ) + host = solve(discretize(pdesys, FEMDiscretization(Ω))) + for backend in (KernelAbstractions.CPU(), JLBackend()) + dev = solve(discretize(pdesys, FEMDiscretization(Ω; backend))) + @test dev(0.4, 0.7; dv = U) ≈ host(0.4, 0.7; dv = U) rtol = 1.0e-10 + end +end diff --git a/test/GPU/common/assembly.jl b/test/GPU/common/assembly.jl new file mode 100644 index 00000000..21470834 --- /dev/null +++ b/test/GPU/common/assembly.jl @@ -0,0 +1,104 @@ +# Device assembly end to end on one backend: `discretize` with `backend` set gives the operators of the host assembly, +# and the returned problem solves to the host solution. +using Test +# The four triggers of FiniteElementMethodKAExt. +using KernelAbstractions: KernelAbstractions +using Adapt: Adapt +using GPUArrays: GPUArrays +using GPUArraysCore: GPUArraysCore +using FiniteElementMethod: FiniteElementMethod as FEM, FEMDiscretization, MeshDomain, boundarypiece +using ModelingToolkit: ModelingToolkit, PDESystem, Differential, @parameters, @named, t_nounits as t +using DomainSets: Interval +using Ferrite: Ferrite, generate_grid, Hexahedron, Triangle, Vec, Lagrange, RefTriangle +using OrdinaryDiffEqBDF: DFBDF, solve, discretize +using Symbolics: @variables + +# The operators of `_lower` before the Dirichlet rows are replaced, and the Dirichlet dofs. +function lowered(pdesys, disc) + parts = FEM._lower(pdesys, disc) + return (; parts.raw.M, parts.raw.K, F = parts.raw.load, parts.raw.prescribed) +end + +relerr(a, b) = maximum(abs, a - b) / max(maximum(abs, b), eps()) + +# Against the host Float64 assembly; Float32 rounding of the coefficients and shape functions is about 1e-7. +optol(::Type{Float32}) = 1.0e-5 +optol(::Type{Float64}) = 1.0e-12 +# Solutions of the host and the device problem, both solved with reltol 1e-8. +soltol(::Type{Float32}) = 1.0e-4 +soltol(::Type{Float64}) = 1.0e-7 + +@variables x y z u(..) v(..) +@parameters k +const Dx, Dy, Dz, Dt = Differential(x), Differential(y), Differential(z), Differential(t) + +# 3D P1 on hexahedra: a variable conductivity with a parameter, a source, Dirichlet data on one face. +function heat3d(g; n = 3) + Ω = MeshDomain(generate_grid(Hexahedron, (n, n, n), Vec(0.0, 0.0, 0.0), Vec(1.0, 1.0, 1.0))) + U = u(t, x, y, z) + c = 1 + x^2 + k * y * z + eq = Dt(U) ~ Dx(c * Dx(U)) + Dy(c * Dy(U)) + Dz(c * Dz(U)) + x * y + 1 + bcs = [u(t, boundarypiece(Ω, :left)) ~ g(y, z), u(0, x, y, z) ~ x * (1 - x)] + @named pdesys = PDESystem([eq], bcs, [(x, y, z) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y, z], [U], [k => 0.3]) + return pdesys, Ω, Dict(), (0.4, 0.3, 0.6) +end + +# 2D P2 on triangles. +function heat2d_p2(g; n = 4) + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + U = u(t, x, y) + eq = Dt(U) ~ Dx((1 + k * x) * Dx(U)) + Dy((1 + k * x) * Dy(U)) + sin(x) * y + bcs = [u(t, boundarypiece(Ω, :left)) ~ g(y, 0), u(t, boundarypiece(Ω, :right)) ~ 0.5, u(0, x, y) ~ x * y] + @named pdesys = PDESystem([eq], bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [U], [k => 0.3]) + return pdesys, Ω, Dict(u => Lagrange{RefTriangle, 2}()), (0.4, 0.7) +end + +# Two fields of different orders coupled by linear terms, as in a Taylor–Hood pair. +function two_field(g; n = 3) + Ω = MeshDomain(generate_grid(Triangle, (n, n), Vec(0.0, 0.0), Vec(1.0, 1.0))) + U, V = u(t, x, y), v(t, x, y) + eqs = [Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + Dx(V) + 1, Dt(V) ~ 0.5 * (Dx(Dx(V)) + Dy(Dy(V))) - U + k * Dy(U)] + left = boundarypiece(Ω, :left) + bcs = [u(t, left) ~ g(y, 0), v(t, left) ~ 0, u(0, x, y) ~ 0, v(0, x, y) ~ x] + @named pdesys = PDESystem(eqs, bcs, [(x, y) ∈ Ω, t ∈ Interval(0.0, 0.1)], [t, x, y], [U, V], [k => 0.3]) + return pdesys, Ω, Dict(u => Lagrange{RefTriangle, 2}(), v => Lagrange{RefTriangle, 1}()), (0.4, 0.7) +end + +const CONSTANT_G = (a, b) -> 1.0 +const TIMEDEP_G = (a, b) -> sin(10t) * (1 + a) + b +const ASSEMBLY_CASES = [ + "3D P1 hexahedron" => heat3d, + "2D P2 triangle" => heat2d_p2, + "two fields, P2 and P1" => two_field, +] + +# Every case with constant and time-dependent Dirichlet data, in both precisions and both assembly modes: the +# operators against the host assembly, and the solution at a point against the host solution. +function test_device_assembly(backend; precisions = (Float32, Float64), worst = Dict{Any, Float64}()) + @testset "$name, $gname Dirichlet data on $(nameof(typeof(backend)))" for (name, case) in ASSEMBLY_CASES, + (gname, g) in (("constant", CONSTANT_G), ("time-dependent", TIMEDEP_G)) + pdesys, Ω, spaces, point = case(g) + host_disc = FEMDiscretization(Ω, t; spaces, boundary_check = :off) + host = lowered(pdesys, host_disc) + host_sol = solve(discretize(pdesys, host_disc), DFBDF(); reltol = 1.0e-8, abstol = 1.0e-10) + dvs = pdesys.dvs + for T in precisions, assembly in (:colored, :atomic) + disc = FEMDiscretization(Ω, t; spaces, boundary_check = :off, backend, precision = T, assembly) + dev = lowered(pdesys, disc) + @test dev.prescribed == host.prescribed + for (op, a, b) in (("M", dev.M, host.M), ("K", dev.K, host.K), ("F", dev.F, host.F)) + err = relerr(a, b) + worst[(op, T)] = max(get(worst, (op, T), 0.0), err) + @test err < optol(T) + end + sol = solve(discretize(pdesys, disc), DFBDF(); reltol = 1.0e-8, abstol = 1.0e-10) + for dv in dvs + ref = host_sol(0.1, point...; dv) + err = abs(sol(0.1, point...; dv) - ref) / max(abs(ref), 1.0) + worst[("solution", T)] = max(get(worst, ("solution", T), 0.0), err) + @test err < soltol(T) + end + end + end + return worst +end diff --git a/test/GPU/common/cases.jl b/test/GPU/common/cases.jl index 88f85a24..155d51bd 100644 --- a/test/GPU/common/cases.jl +++ b/test/GPU/common/cases.jl @@ -91,13 +91,10 @@ function kernel_rows(pdesys, test_space) 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)) + for (i, ((_, _, ex), (_, _, g))) in enumerate(zip(emit_dirichlet(an; expression = Val(true)), emit_dirichlet(an))) push!(rows, ("dirichlet$i", ex, g, :dirichlet)) end - return rows, length(s.P) + return rows, length(an.slots.P) end # Every `(case, role, Expr, host function, signature, number of parameters)` of `CASES`. diff --git a/test/GPU/extension.jl b/test/GPU/extension.jl new file mode 100644 index 00000000..c8676de9 --- /dev/null +++ b/test/GPU/extension.jl @@ -0,0 +1,48 @@ +# Loading and refusals of device assembly: the FEM and Ferrite extensions it needs, the keywords' validation, the +# error when a Ferrite without GPU support is loaded, and the features device assembly does not cover yet. +using JLArrays: JLBackend +using GenericSparseArrays: GenericSparseArrays +include(joinpath(@__DIR__, "common", "assembly.jl")) + +const Ext = Base.get_extension(FEM, :FiniteElementMethodKAExt) + +@testset "the FEM and Ferrite KernelAbstractions extensions are both loaded" begin + @test Ext isa Module + @test Base.get_extension(FEM, :FiniteElementMethodGenericSparseArraysExt) isa Module + @test Base.get_extension(Ferrite, :FerriteKAExt) isa Module + @test FEM.is_device_backend(KernelAbstractions.CPU()) && FEM.is_device_backend(JLBackend()) + @test FEM.device_matrix_type(JLBackend(), Float32, Int) <: GenericSparseArrays.GenericSparseMatrixCSC +end + +@testset "the error when Ferrite has no GPU support names what is missing" begin + @test_throws "device assembly needs a Ferrite with GPU support (the FerriteKAExt extension, Ferrite.jl PR #1496)" Ext.check_ferrite_gpu(nothing) +end + +@testset "the keywords are validated at construction" begin + pdesys, Ω, spaces, _ = heat2d_p2(CONSTANT_G) + @test_throws "backend must be a KernelAbstractions.Backend, such as ROCBackend() or KernelAbstractions.CPU(), or nothing; got :rocm" FEMDiscretization(Ω, t; backend = :rocm) + @test_throws "precision must be Float32, Float64 or nothing, got Float16" FEMDiscretization(Ω, t; backend = JLBackend(), precision = Float16) + @test_throws "precision = Float32 sets the precision of device assembly, so it needs a backend" FEMDiscretization(Ω, t; precision = Float32) + @test_throws "assembly must be :colored or :atomic, got :serial" FEMDiscretization(Ω, t; backend = JLBackend(), assembly = :serial) + # neither is forwarded to the problem + prob = discretize(pdesys, FEMDiscretization(Ω, t; spaces, backend = JLBackend(), precision = Float32)) + @test !any(in((:backend, :precision, :assembly)), keys(prob.kwargs)) +end + +@testset "features device assembly does not cover raise an ArgumentError naming them" begin + Ω = MeshDomain(generate_grid(Triangle, (2, 2), Vec(0.0, 0.0), Vec(1.0, 1.0))) + left, right = boundarypiece(Ω, :left), boundarypiece(Ω, :right) + U = u(t, x, y) + sys(eq, bcs) = PDESystem([eq], [bcs; u(0, x, y) ~ 0], [(x, y) ∈ Ω, t ∈ Interval(0.0, 1.0)], [t, x, y], [U], []; name = :p) + diffusion = Dx(Dx(U)) + Dy(Dy(U)) + dev(; kw...) = FEMDiscretization(Ω, t; backend = JLBackend(), kw...) + msg(what) = "backend = $(JLBackend()): device assembly does not support $what yet; remove the backend keyword to assemble on the host" + @test_throws msg("facet terms (Neumann and Robin conditions)") discretize(sys(Dt(U) ~ diffusion, [u(t, left) ~ 0, FEM.NormalDerivative(right)(u(t, right)) ~ 1]), dev()) + @test_throws msg("nonlinear terms") discretize(sys(Dt(U) ~ diffusion - U^3, [u(t, left) ~ 0]), dev()) + @test_throws msg("sources that depend on time") discretize(sys(Dt(U) ~ diffusion + sin(t), [u(t, left) ~ 0]), dev()) + @test_throws msg("dirichlet = :eliminate (use the default dirichlet = :algebraic)") discretize(sys(Dt(U) ~ diffusion, [u(t, left) ~ 0]), dev(dirichlet = :eliminate)) + @test_throws msg("the SUPG test space") discretize( + sys(Dt(U) ~ 0.01 * diffusion - Dx(U), [u(t, left) ~ 0, u(t, right) ~ 1]), + dev(test_space = FEM.SUPG((hK, b) -> hK / 2)) + ) +end diff --git a/test/GPU/vendor/amdgpu/Project.toml b/test/GPU/vendor/amdgpu/Project.toml index 69e93124..f7c24268 100644 --- a/test/GPU/vendor/amdgpu/Project.toml +++ b/test/GPU/vendor/amdgpu/Project.toml @@ -12,6 +12,7 @@ KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" NaNMath = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3" +OrdinaryDiffEqBDF = "6ad6398a-0878-4a85-9266-38940aa047c8" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" @@ -19,6 +20,7 @@ Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [sources] +Ferrite = {url = "https://github.com/Ferrite-FEM/Ferrite.jl", rev = "do/gpu-ci"} FiniteElementMethod = {path = "../../../.."} [compat] @@ -34,6 +36,7 @@ KernelAbstractions = "0.9" LinearAlgebra = "1" ModelingToolkit = "11" NaNMath = "1.1.5" +OrdinaryDiffEqBDF = "2.4.1" Random = "1" SafeTestsets = "0.1" SparseArrays = "1" diff --git a/test/GPU/vendor/amdgpu/runtests.jl b/test/GPU/vendor/amdgpu/runtests.jl index 16ac49a4..4b8dda0d 100644 --- a/test/GPU/vendor/amdgpu/runtests.jl +++ b/test/GPU/vendor/amdgpu/runtests.jl @@ -35,3 +35,16 @@ println("KernelAbstractions ", pkgversion(KernelAbstractions), ", AMDGPU ", pkgv @test checked > 0 end end + +# Device assembly through `discretize` on ROCBackend(), in its own module: `common/assembly.jl` names its own symbolic +# variables. Float64 runs at about 1/53 of the Float32 rate on Radeon 8060S, so the cases are small. +module DeviceAssemblyAMDGPU + using AMDGPU: AMDGPU, ROCBackend + include(joinpath(@__DIR__, "..", "..", "common", "assembly.jl")) + @testset "device assembly on AMDGPU" begin + @test Base.get_extension(FEM, :FiniteElementMethodAMDGPUExt) isa Module + @test Base.get_extension(Ferrite, :FerriteAMDGPUExt) isa Module + @test FEM.device_matrix_type(ROCBackend(), Float32, Int) <: AMDGPU.rocSPARSE.ROCSparseMatrixCSC + println("largest relative errors on ROCBackend(): ", test_device_assembly(ROCBackend())) + end +end