Skip to content

Precompilation can lead to Dual tag ordering problems #714

Description

@Technici4n

Hi, I found an issue when working with precompilation and nested derivatives.

The tag count system is setup such that the inner derivative receives a tag with a higher tagcount than the outer derivative. When precompiling, it can happen that only the outer derivative is precompiled, for example because of runtime dispatch that depends on the value of some parameters. When running the code later, the atomic counter for tags starts from 0 again, which can cause the inner derivative to be given a tag with a lower count. This leads to a Cannot determine ordering of Dual tags error.

Here is a reproduction example: https://github.com/Technici4n/FDPrecompilationIssue.
Precompilation should succeed, and running the test should fail with the following output:

     Testing Running tests...
Tag count of Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}}(0,1) is 1
Tag count of Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#1#2"{ForwardDiff.Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}, Int64, 1}}, ForwardDiff.Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}, Int64, 1}}}(Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}}(0,0),Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}}(0,2)) is 0
ERROR: LoadError: Cannot determine ordering of Dual tags ForwardDiff.Tag{FDPrecompilationIssue.var"#1#2"{ForwardDiff.Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}, Int64, 1}}, ForwardDiff.Dual{ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}, Int64, 1}} and ForwardDiff.Tag{FDPrecompilationIssue.var"#3#4"{Int64}, Int64}

(I encountered this issue was encountered in the context of https://github.com/mfherbst/AiidaDFTK.jl but the setup is more complicated than in this minimal reproduction example. AiidaDFTK precompiles a stress computation (outer derivative) using the LDA functional (does not require a nested derivative). I encountered the issue when running a stress computation through AiidaDFTK using a PBE functional (which requires a nested gradient). You can think of α from the reproduction example as the parameter that selects the functional, LDA as α = 0, PBE as α = 1.)

Activity

  1. gdalle commented on Oct 30, 2024

    @gdalle
    Member

    Is there a way to detect from inside the package if we're currently pre-compiling it? If so, maybe the tag counter could be initialized at typemin(Int) instead of 0?

  2. gdalle commented on Oct 30, 2024

    @gdalle
    Member

    Although I'm not sure I understand why the counter restarts at zero, shouldn't it be the same state as it was at the end of precompilation?

    https://www.oxinabox.net/2023/06/16/top-level-code-in-julia.html

  3. KristofferC commented on Oct 31, 2024

    @KristofferC
    Collaborator

    TAGCOUNT is zero when ForwardDiff finishes precompiling. Mutations to it during precompilation of another package cannot change that.

  4. added a commit that references this issue on Nov 18, 2024
    4cb3336
  5. itme-yaboi commented on Nov 3, 2026

    @itme-yaboi

    Ran into this issue and ended up having to use claude to debug/replicate, after finding the bug ended up here. Results and a solution that worked for our case is below (Instead of trusting the counter, look at the types):

    We hit this in a downstream thermodynamics package as a fresh-session failure: the first stiff solve in a new session fails, and the same solve passes if any other ForwardDiff call has run earlier in the session. Here is a reproducer that uses only OrdinaryDiffEqRosenbrock and ForwardDiff:

    using OrdinaryDiffEqRosenbrock, ForwardDiff
    const FD = ForwardDiff
    "warm" in ARGS && FD.derivative(sin, 1.0)    # any ForwardDiff call before the solve avoids the failure
    struct G{U}; u::U; end                        # the inner function; holds the state u
    (g::G)(e) = sum([e[1], g.u[1]] .^ 2) + e[2]   # mixes inner duals with an entry of u (promotion)
    function f!(du, u, p, t)
        # The Float64 branch stands in for a Float64 path whose tag was precompiled in a package, so the
        # first tag this session creates is the inner gradient's, taken at the solver's Dual point.
        g = u isa Vector{Float64} ? [2u[1], 1.0] : FD.gradient(G(u), u)
        du[1] = -g[1]; du[2] = -u[2]
    end
    try
        solve(ODEProblem(f!, [1.0, 1.0], (0.0, 1.0)), Rodas5P()); println("solved")
    catch err
        println(sprint(showerror, hasproperty(err, :e) ? err.e : err))
    end
    const TD = FD.Tag{OrdinaryDiffEqRosenbrock.OrdinaryDiffEqCore.DiffEqBase.OrdinaryDiffEqTag, Float64}
    const TI = FD.Tag{G{Vector{FD.Dual{TD,Float64,1}}}, FD.Dual{TD,Float64,1}}
    println("TAGCOUNT[] = ", Int(FD.TAGCOUNT[]), ", tagcount(TD) = ", FD.tagcount(TD), ", tagcount(TI) = ", FD.tagcount(TI))
    println("TD ≺ TI = ", FD.:≺(TD, TI), ", TI ≺ TD = ", FD.:≺(TI, TD))

    julia --project mwe.jl, in a fresh process:

    type Dual has field offset -1392590848 that exceeds the page size
    TAGCOUNT[] = 2, tagcount(TD) = 0, tagcount(TI) = 0
    TD ≺ TI = false, TI ≺ TD = false
    

    julia --project mwe.jl warm:

    solved
    TAGCOUNT[] = 3, tagcount(TD) = 0, tagcount(TI) = 1
    TD ≺ TI = true, TI ≺ TD = false
    

    The result is the same on repeated fresh runs. If the inner function has no promotion (e[1]^2 * g.u[1] + e[2]), the same tie gives MethodError: no method matching Float64(::Dual{Tag{G{…}, Dual{Tag{OrdinaryDiffEqTag, Float64}, Float64, 1}}, …}) instead, wrapped in FirstAutodiffJacError. In our package the Float64 path is precompiled, so its tag takes no count at runtime. Without the u isa Vector{Float64} branch, the solver's first Float64 call to f! takes count 0 and the failure does not appear.

    Versions: Julia 1.13.2 (Windows x86_64), ForwardDiff 1.4.7, OrdinaryDiffEqRosenbrock 2.7.5, OrdinaryDiffEqCore 4.19.1, DiffEqBase 7.21.5.

    Mechanism. The count of Tag{OrdinaryDiffEqTag, Float64}, 0, is baked into a package image. The session's counter also starts at 0, so the first tag created at runtime ties with it; here that is the gradient tag taken at the solver's Dual point. With ≺ false both ways, promote_rule(Dual{TD}, Dual{TI,Dual{TD}}) and its reverse each put the other tag outermost. So promote_type never agrees, and the nested type grows until the layout overflows.

    Containment ordering. We now order a tag after any tag whose duals appear in its value type V. This is the V half of #820's containment check (we do not walk F), with tagcount as the fallback. With that rule, the reproducer and our package's fresh sessions pass. We ran the rule against #807's two counterexamples, the counterexample from the #820 review, and the tests added in #820 and #853, each in fresh processes on ForwardDiff 1.4.7:

    We also baked every order and tie of the tag counts for those shapes. No variant that passes on 1.4.7 fails with the rule. The intransitivity noted in the #820 review applies here too: a mix of containment and count fallback can give a cyclic order, which ran correctly in the cases we tried.

    We would be glad to run this reproducer, and our package's suite, against #853.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions