diff --git a/src/assembly.jl b/src/assembly.jl index 29ab49bb..d8bf9f6e 100644 --- a/src/assembly.jl +++ b/src/assembly.jl @@ -134,7 +134,7 @@ function assemble_linear!(M, K, F, ctx::AssemblyContext, kernels, p; t = 0.0, ki aM = Ferrite.start_assemble(M; fillzero = :mass in kinds) aK = Ferrite.start_assemble(K; fillzero = :bilinear in kinds) :source in kinds && fill!(F, 0) - op = LinearOp(aM, aK, F, zeros(ne, ne), zeros(ne, ne), zeros(ne)) + op = LinearOp(aM, aK, F, zeros(eltype(M), ne, ne), zeros(eltype(K), ne, ne), zeros(eltype(F), ne)) _assemble!(op, ctx, _split(ctx, kernels, kinds)..., p, t) return M, K, F end @@ -155,22 +155,23 @@ end function assemble_nonlinear!(r, J, ctx::AssemblyContext, kernels, u, p; t = 0.0) ne = _max_ndofs(ctx.dh) fill!(r, 0) - op = NonlinearOp(Ferrite.start_assemble(J), r, zeros(ne, ne), zeros(ne), u, zeros(ne)) + T = eltype(r) + op = NonlinearOp(Ferrite.start_assemble(J), r, zeros(eltype(J), ne, ne), zeros(T, ne), u, zeros(T, ne)) _assemble!(op, ctx, _split(ctx, kernels, (:nonlinear,))..., p, t) return r, J end -struct LinearOp{AM, AK, FV <: AbstractVector{Float64}, ME <: AbstractMatrix{Float64}, FE <: AbstractVector{Float64}} +struct LinearOp{AM, AK, FV <: AbstractVector{<:AbstractFloat}, ME <: AbstractMatrix{<:AbstractFloat}, KE <: AbstractMatrix{<:AbstractFloat}, FE <: AbstractVector{<:AbstractFloat}} aM::AM aK::AK F::FV Me::ME - Ke::ME + Ke::KE Fe::FE end # `aJ === nothing` assembles the residual only. -struct NonlinearOp{AJ, R <: AbstractVector{Float64}, U, JE <: AbstractMatrix{Float64}, RE <: AbstractVector{Float64}} +struct NonlinearOp{AJ, R <: AbstractVector{<:AbstractFloat}, U, JE <: AbstractMatrix{<:AbstractFloat}, RE <: AbstractVector{<:AbstractFloat}} aJ::AJ r::R Je::JE diff --git a/src/frontend.jl b/src/frontend.jl index 7b052c51..6b2731d0 100644 --- a/src/frontend.jl +++ b/src/frontend.jl @@ -264,7 +264,7 @@ _finish_cell!(op::LinearOp{Nothing, Nothing}, dofs) = (Ferrite.assemble!(op.F, d function assemble_sources!(F, ctx::AssemblyContext, kernels, p, t) fill!(F, 0) ne = _max_ndofs(ctx.dh) - op = LinearOp(nothing, nothing, F, zeros(ne, ne), zeros(ne, ne), zeros(ne)) + op = LinearOp(nothing, nothing, F, zeros(ne, ne), zeros(ne, ne), zeros(eltype(F), ne)) _assemble!(op, ctx, _split(ctx, kernels, (:source,))..., p, t) return F end diff --git a/src/numeric_dae.jl b/src/numeric_dae.jl index d34d7a2c..863aea17 100644 --- a/src/numeric_dae.jl +++ b/src/numeric_dae.jl @@ -3,10 +3,13 @@ Opaque wrapper for an assembled operator, used as a non-tunable `System` parameter so that ModelingToolkit neither flattens it into the tunable vector nor scans it element by element. +`A` keeps its floating-point element type; any other matrix is converted to +`SparseMatrixCSC{Float64, Int}`. """ -struct FEMOp - A::SparseMatrixCSC{Float64, Int} +struct FEMOp{T <: AbstractFloat} + A::SparseMatrixCSC{T, Int} end +FEMOp(A) = FEMOp{Float64}(A) Base.show(io::IO, ::FEMOp) = print(io, "FEMOp") """ @@ -107,23 +110,28 @@ so problems sharing this wrapper (remakes, ensembles) can be solved concurrently After [`eliminate_dirichlet`](@ref) the wrapper evaluates `N` at the full state rebuilt from the free dofs with `u_d = g_d`, and keeps its free rows and its `[free, free]` Jacobian block. -The element pipeline is `Float64`: `N` is evaluated at `Float64` states and at first-order -`ForwardDiff.Dual`s of `Float64` (as the default initializer passes), whose partials go through -the analytic tangent. Any other state, such as `Float32`, `BigFloat`, `Dual`s of those or nested -`Dual`s, throws `ArgumentError("the nonlinear operator evaluates Float64 states and first-order -ForwardDiff Duals of Float64; got T")` with `T` the state's element type; its Jacobian is -evaluated at `Float64` states only and otherwise throws `ArgumentError("the nonlinear -operator's Jacobian evaluates Float64 states; got T")`. +`N` is evaluated at `AbstractFloat` states, such as `Float64` or `Float32`, and at first-order +`ForwardDiff.Dual`s of those (as the default initializer passes), whose partials go through the +analytic tangent; the element buffers of `op` keep their own element type, `Float64` from +[`NonlinearOperator`](@ref). Any other state, such as nested `Dual`s, throws +`ArgumentError("the nonlinear operator evaluates AbstractFloat states and first-order +ForwardDiff Duals of them; got T")` with `T` the state's element type; its Jacobian is +evaluated at `AbstractFloat` states only and otherwise throws `ArgumentError("the nonlinear +operator's Jacobian evaluates AbstractFloat states; got T")`. `p` keeps a floating-point +element type and is converted to `Float64` otherwise. """ -struct FEMNonlinear +struct FEMNonlinear{T <: AbstractFloat} op::Any - p::Vector{Float64} + p::Vector{T} prescribed::BitVector pool::Vector{Any} lock::ReentrantLock elimination::Any # `nothing`, or `(e::DirichletElimination, nzmap)` with `nzmap` the positions of `J_N[free, free]` in `J_N` end -FEMNonlinear(op, p, prescribed = falses(0)) = FEMNonlinear(op, collect(Float64, p), prescribed, Any[], ReentrantLock(), nothing) +function FEMNonlinear(op, p, prescribed = falses(0)) + T = eltype(p) <: AbstractFloat ? eltype(p) : Float64 + return FEMNonlinear(op, collect(T, p), prescribed, Any[], ReentrantLock(), nothing) +end Base.show(io::IO, ::FEMNonlinear) = print(io, "FEMNonlinear") # `f(op)` with an operator no other running call holds; the pool grows to the number of concurrent calls. @@ -137,9 +145,9 @@ function with_operator(f, N::FEMNonlinear) end end -check_state(::AbstractVector{Float64}) = nothing -check_state(::AbstractVector{<:ForwardDiff.Dual{<:Any, Float64}}) = nothing -check_state(u) = throw(ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $(eltype(u))")) +check_state(::AbstractVector{<:AbstractFloat}) = nothing +check_state(::AbstractVector{<:ForwardDiff.Dual{<:Any, <:AbstractFloat}}) = nothing +check_state(u) = throw(ArgumentError("the nonlinear operator evaluates AbstractFloat states and first-order ForwardDiff Duals of them; got $(eltype(u))")) # `r .+= N(u, t)` outside the prescribed rows. After elimination `u` and `r` hold the free dofs only. function add_nonlinear!(r, N::FEMNonlinear, u, t) @@ -161,8 +169,8 @@ function add_full_nonlinear!(r, N::FEMNonlinear, u, t) end # ForwardDiff states, as from the default initializer's NewtonRaphson: the partials are pushed through the -# analytic tangent, `∂N(u) = J_N(value(u)) ∂u`, since the element buffers hold `Float64`. -function add_full_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, Float64, P}}, t) where {T, P} +# analytic tangent, `∂N(u) = J_N(value(u)) ∂u`, since the element buffers hold plain floats. +function add_full_nonlinear!(r, N::FEMNonlinear, u::AbstractVector{ForwardDiff.Dual{T, V, P}}, t) where {T, V <: AbstractFloat, P} du = [ForwardDiff.partials(x, k) for x in u, k in 1:P] return with_operator(N) do op J = jacobian!(op.J, op, ForwardDiff.value.(u), N.p, t) @@ -178,8 +186,8 @@ nonlinear_residual!(r, N::FEMNonlinear, u, t) = add_nonlinear!(fill!(r, 0), N, u # `nonzeros(J) .+= nonzeros(∂N/∂u)` outside the prescribed rows; `J` must have the pattern of `N`'s Jacobian. function add_nonlinear_jacobian!(J, N::FEMNonlinear, u, t) - u isa AbstractVector{Float64} || - throw(ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got $(eltype(u))")) + u isa AbstractVector{<:AbstractFloat} || + throw(ArgumentError("the nonlinear operator's Jacobian evaluates AbstractFloat states; got $(eltype(u))")) elimination = N.elimination return with_operator(N) do op if elimination === nothing @@ -397,7 +405,9 @@ function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothin D = Differential(iv) us = unknowns === nothing ? [only(@variables $field(iv)[1:length(r)]) for (field, r) in ops.fields] : collect(unknowns) - @parameters Mop::FEMOp [tunable = false] Kop::FEMOp [tunable = false] Fop::FEMLoad [tunable = false] + # MTKParameters needs a concrete (DataType) symtype for a non-numeric parameter, not the UnionAll `FEMOp`. + OpT = FEMOp{eltype(ops.K)} + @parameters Mop::OpT [tunable = false] Kop::OpT [tunable = false] Fop::FEMLoad [tunable = false] ranges = last.(ops.fields) linear(ri) = sum(fem_apply(Mop, ri, rj, D(uj)) + fem_apply(Kop, ri, rj, uj) for (rj, uj) in zip(ranges, us)) ps = Any[Mop, Kop, Fop] @@ -405,7 +415,8 @@ function fem_system(ops::FEMOperators, iv; unknowns = nothing, metadata = nothin if ops.nonlinear === nothing eqs = [fem_load(Fop, ri, iv) ~ linear(ri) for ri in ranges] else - @parameters Nop::FEMNonlinear [tunable = false] + NonlinearT = typeof(ops.nonlinear) + @parameters Nop::NonlinearT [tunable = false] push!(ps, Nop) state = foldl(fem_cat, us) eqs = [fem_load(Fop, ri, iv) ~ linear(ri) + fem_nonlinear(Nop, ri, iv, state) for ri in ranges] diff --git a/src/operators.jl b/src/operators.jl index f1f5dddc..06d1ba21 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -7,15 +7,15 @@ The `:nonlinear` kernels of `kernels` on `ctx`, with preallocated residual `r`, `allocate_matrix(dh, ch)`) and element scratch. Use [`residual!`](@ref), [`jacobian!`](@ref) and [`residual_jacobian!`](@ref); `op(r, u, p, t)` is `residual!(r, op, u, p, t)`. """ -struct NonlinearOperator{C <: AssemblyContext, V <: Tuple, G <: Tuple, JT} +struct NonlinearOperator{C <: AssemblyContext, V <: Tuple, G <: Tuple, JT, T <: AbstractFloat} ctx::C volume::V groups::G - r::Vector{Float64} + r::Vector{T} J::JT - Je::Matrix{Float64} - re::Vector{Float64} - u_elem::Vector{Float64} + Je::Matrix{T} + re::Vector{T} + u_elem::Vector{T} end function NonlinearOperator(ctx::AssemblyContext, kernels; ch = nothing) diff --git a/test/Assembly/float32.jl b/test/Assembly/float32.jl new file mode 100644 index 00000000..d167b865 --- /dev/null +++ b/test/Assembly/float32.jl @@ -0,0 +1,108 @@ +# Element-type-generic assembly: the generated kernels of a heat problem assembled into Float32 storage, on a Float32 +# grid with Float32 values and parameters, against the Float64 assembly. The kernels' Float64 literals promote +# inside each call, so the Float32 results are the Float64 ones rounded at the element level. +using FiniteElementMethod: weak_form, emit_kernels, AssemblyContext, assemble_linear, assemble_linear!, + assemble_nonlinear, assemble_nonlinear!, NonlinearOperator, residual!, jacobian! +using Ferrite, LinearAlgebra, Random, SparseArrays, Symbolics, Test + +include(joinpath(@__DIR__, "..", "shared", "strongform_seam.jl")) +using .StrongFormSeam: analyse + +relerr(A, B) = norm(A - B) / norm(B) + +@variables t x y k +@variables u(..) +Dx, Dy, Dt = Differential(x), Differential(y), Differential(t) +U = u(t, x, y) + +function context(T, n) + grid = generate_grid(Triangle, (n, n), Vec{2, T}((-1, -1)), Vec{2, T}((1, 1))) + ip = Lagrange{RefTriangle, 1}() + dh = DofHandler(grid) + add!(dh, :u, ip) + close!(dh) + cv = CellValues(T, QuadratureRule{RefTriangle}(T, 2), ip) + fv = FacetValues(T, FacetQuadratureRule{RefTriangle}(T, 2), ip) + return AssemblyContext(dh, [:u], cv, fv) +end + +linear_kernels() = emit_kernels( + weak_form( + analyse( + [Dt(U) ~ Dx(k * Dx(U)) + Dy(k * Dy(U)) + (1 + t) * x * y + 1], []; + depvars = [U], t, sivs = [x, y], params = [k] + ) + ) +) +nonlinear_kernels() = emit_kernels( + weak_form( + analyse( + [0 ~ Dx((1 + U^2) * Dx(U)) + Dy((1 + U^2) * Dy(U)) + 1], []; + depvars = [U], t, sivs = [x, y] + ) + ) +) + +@testset "Float32 assembly of M, K, F matches Float64" begin + kernels = linear_kernels() + ctx64, ctx32 = context(Float64, 8), context(Float32, 8) + ref = assemble_linear(ctx64, kernels, [2.0]; t = 0.5) + @test ref.M isa SparseMatrixCSC{Float64, Int} && ref.K isa SparseMatrixCSC{Float64, Int} && ref.F isa Vector{Float64} + + M = allocate_matrix(SparseMatrixCSC{Float32, Int}, ctx32.dh) + K, F = copy(M), zeros(Float32, ndofs(ctx32.dh)) + @test assemble_linear!(M, K, F, ctx32, kernels, Float32[2]; t = 0.5f0) === (M, K, F) + @test eltype(M) == eltype(K) == eltype(F) == Float32 + for (A, B) in ((M, ref.M), (K, ref.K), (F, ref.F)) + @test norm(B) > 0 + @test relerr(A, B) ≤ 1.0e-5 + end +end + +@testset "M and K are each accumulated in their own element type" begin + # A mass coefficient whose element entries overflow Float32 but not Float64. + ρ = 1.0e40 + kernels = emit_kernels( + weak_form( + analyse([ρ * Dt(U) ~ Dx(Dx(U)) + Dy(Dy(U)) + 1], []; depvars = [U], t, sivs = [x, y]) + ) + ) + ctx = context(Float64, 4) + ref = assemble_linear(ctx, kernels, [0.0]) + @test all(isfinite, nonzeros(ref.M)) && maximum(abs, nonzeros(ref.M)) > floatmax(Float32) + for (TM, TK) in ((Float64, Float32), (Float32, Float64)) + M = allocate_matrix(SparseMatrixCSC{TM, Int}, ctx.dh) + K = allocate_matrix(SparseMatrixCSC{TK, Int}, ctx.dh) + F = zeros(ndofs(ctx.dh)) + assemble_linear!(M, K, F, ctx, kernels, [0.0]) + @test eltype(M) == TM && eltype(K) == TK + @test all(isfinite, nonzeros(K)) && relerr(K, ref.K) ≤ 1.0e-6 + if TM == Float64 + @test M == ref.M + else + @test any(isinf, nonzeros(M)) + end + end +end + +@testset "Float32 nonlinear residual and Jacobian match Float64" begin + kernels = nonlinear_kernels() + ctx64, ctx32 = context(Float64, 8), context(Float32, 8) + n = ndofs(ctx64.dh) + u = 0.5 .* randn(Xoshiro(4), n) + ref = assemble_nonlinear(ctx64, kernels, u, [0.0]) + @test ref.r isa Vector{Float64} && ref.J isa SparseMatrixCSC{Float64, Int} + + r, J = zeros(Float32, n), allocate_matrix(SparseMatrixCSC{Float32, Int}, ctx32.dh) + assemble_nonlinear!(r, J, ctx32, kernels, Float32.(u), Float32[0]) + @test eltype(r) == eltype(J) == Float32 + @test relerr(r, ref.r) ≤ 1.0e-5 + @test relerr(J, ref.J) ≤ 1.0e-5 + + # A NonlinearOperator with Float32 buffers, evaluated through its in-place entry points. + op64 = NonlinearOperator(ctx64, kernels) + @test typeof(op64.r) == Vector{Float64} && typeof(op64.Je) == Matrix{Float64} + op = NonlinearOperator(ctx32, op64.volume, op64.groups, Float32.(op64.r), J, Float32.(op64.Je), Float32.(op64.re), Float32.(op64.u_elem)) + @test residual!(zeros(Float32, n), op, Float32.(u), Float32[0], 0.0f0) ≈ r + @test jacobian!(similar(J), op, Float32.(u), Float32[0], 0.0f0) ≈ J +end diff --git a/test/shared/frontend_tests/nonlinear.jl b/test/shared/frontend_tests/nonlinear.jl index 950c1e24..258f2b24 100644 --- a/test/shared/frontend_tests/nonlinear.jl +++ b/test/shared/frontend_tests/nonlinear.jl @@ -164,33 +164,53 @@ end Threads.nthreads() > 1 || @info "the remakes were solved on one thread, so this test cannot see a race; run with JULIA_NUM_THREADS > 1" end - @testset "states other than Float64 and Dual{Float64} are rejected" begin + @testset "AbstractFloat states and their Duals are evaluated, nested Duals are rejected" begin Ω = square() eq = Dt(U) ~ Dx((1 + U^2) * Dx(U)) + Dy(Dy(U)) + (1 + x + 2y) - 2 * ustar * (1 + t)^2 prob = DAEProblem(pdesystem([eq], [dirichlet(Ω); ic], Ω), FEMDiscretization(Ω, t)) n = length(prob.u0) Dual = FiniteElementMethod.ForwardDiff.Dual - states = ( - Float32.(prob.u0), big.(prob.u0), Dual{Nothing}.(Float32.(prob.u0), 1.0f0), - Dual{:outer}.(Dual{:inner}.(prob.u0, 1.0), Dual{:inner}(1.0, 0.0)), - ) - for u in states - T = eltype(u) - msg = "the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got $T" - @test_throws ArgumentError(msg) prob.f(zeros(T, n), zeros(T, n), u, prob.p, 0.0) + value = FiniteElementMethod.ForwardDiff.value + u0 = prob.u0 .+ 0.1 .* sin.(1:n) + du = cos.(1:n) + r = zeros(n) + prob.f(r, du, u0, prob.p, 0.5) + @test norm(r) > 0 + J = copy(prob.f.jac_prototype) + prob.f.jac(J, du, u0, prob.p, 2.0, 0.5) + + # The residual and Jacobian at a Float32 state, stored as Float32, are the Float64 ones rounded. + r32 = zeros(Float32, n) + prob.f(r32, Float32.(du), Float32.(u0), prob.p, 0.5) + @test norm(r32 - r) / norm(r) ≤ 1.0e-5 + J32 = copy(prob.f.jac_prototype) + prob.f.jac(J32, Float32.(du), Float32.(u0), prob.p, 2.0, 0.5) + @test norm(J32 - J) / norm(J) ≤ 1.0e-5 + rbig = zeros(BigFloat, n) + prob.f(rbig, big.(du), big.(u0), prob.p, 0.5) + @test rbig ≈ r + # Duals of either, as the default initializer passes them: the values are the residual at the values, and + # the partials along the unit direction are J_N + K times it, the Jacobian at γ = 0. + J0 = copy(prob.f.jac_prototype) + prob.f.jac(J0, du, u0, prob.p, 0.0, 0.5) + r0 = zeros(n) + prob.f(r0, zeros(n), u0, prob.p, 0.5) + for V in (Float64, Float32) + rd = zeros(Dual{Nothing, V, 1}, n) + prob.f(rd, zeros(V, n), Dual{Nothing}.(V.(u0), one(V)), prob.p, 0.5) + @test norm(value.(rd) - r0) ≤ 1.0e-5 * norm(r0) + ∂r = [FiniteElementMethod.ForwardDiff.partials(d, 1) for d in rd] + @test norm(∂r - J0 * ones(n)) ≤ 1.0e-5 * norm(J0 * ones(n)) end - @test_throws ArgumentError("the nonlinear operator evaluates Float64 states and first-order ForwardDiff Duals of Float64; got Float32") prob.f( - zeros(Float32, n), zeros(Float32, n), Float32.(prob.u0), prob.p, 0.0 + + nested = Dual{:outer}.(Dual{:inner}.(u0, 1.0), Dual{:inner}(1.0, 0.0)) + T = eltype(nested) + @test_throws ArgumentError("the nonlinear operator evaluates AbstractFloat states and first-order ForwardDiff Duals of them; got $T") prob.f( + zeros(T, n), zeros(T, n), nested, prob.p, 0.0 ) - @test_throws ArgumentError("the nonlinear operator's Jacobian evaluates Float64 states; got Float32") prob.f.jac( - copy(prob.f.jac_prototype), zeros(n), Float32.(prob.u0), prob.p, 1.0, 0.0 + @test_throws ArgumentError("the nonlinear operator's Jacobian evaluates AbstractFloat states; got $T") prob.f.jac( + copy(prob.f.jac_prototype), zeros(n), nested, prob.p, 1.0, 0.0 ) - # The supported states still evaluate: Float64 and a first-order Dual of Float64. - r = zeros(n) - prob.f(r, zeros(n), prob.u0, prob.p, 0.0) - rd = zeros(Dual{Nothing, Float64, 1}, n) - prob.f(rd, zeros(n), Dual{Nothing}.(prob.u0, 1.0), prob.p, 0.0) - @test FiniteElementMethod.ForwardDiff.value.(rd) ≈ r end @testset "steady nonlinear diffusion, dirichlet = $dirichlet" for dirichlet in (:algebraic, :eliminate)