Skip to content

added: ExplicitMPC now support AD with Mooncake.jl + warn_cond kwarg - #529

Merged
franckgaga merged 16 commits into
mainfrom
weight_cov
Nov 25, 2026
Merged

franckgaga merged 16 commits into
mainfrom
weight_cov

Conversation

@franckgaga

@franckgaga franckgaga commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

This PR introduces necessary modifications to support ExplicitMPC differentiation with Mooncake.jl. It also introduces various improvements in the codebase:

  • A new warn_cond=1e6 keyword argument in LinMPC and ExplicitMPC constructor, to change the warning threshold for the condition number of the QP Hessian. Set to warn_cond=Inf to entirely skip this checkup.
  • The inverse covariance matrices invP̄, invQ̂_He and invR̂_He are only required for the MovingHorizonEstimator. The KalmanCovariances constructor hence no longer computes them for all the other StateEstimator types.
  • A new empty_similar helper that returns an empty matrix of the same type as the one in argument, and assert the return type. This helper is super useful on Julia v1.10 (LTS), since it does not support direct conversion from Matrix to Diagonal, even if the original Matrix has non-zero values only on the main diagonal. In any case, it should never happen in this package, so the assertion is an additional safety net for this.

Matrix inversion is avoided what all the `KalmanEstimator` except `MovingHorizonEstimator`
It can me manually disabled with `warn_cond=Inf`, so the `try` block is no longer necessary. The block also needs to be removed for `Mooncake.jl` autodiff.
The `cond` call must not appear in the call stack at all, not even in `if` branch that is never executed.
Making it a separate allow creating in a exception for Mooncake, with the `@mooncake_overlay` mechanism.
This is necessary for `ForwardDiff` AD.
@franckgaga franckgaga changed the title added: ExplicitMPC now support AD with Mooncake.jl added: ExplicitMPC now support AD with Mooncake.jl and warn_cond keyword argument Nov 24, 2026
@franckgaga franckgaga changed the title added: ExplicitMPC now support AD with Mooncake.jl and warn_cond keyword argument added: ExplicitMPC now support AD with Mooncake.jl + warn_cond kw arg Nov 24, 2026
@franckgaga

franckgaga commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

@PTWaade

Now Mooncake.jl is also supported in ExplicitMPC constructor. But it needs a special Mooncake.@mooncake_overlay instruction, however, since a @warn call make it crashes, even if the code path is never reached (for example, in a if block with an always false condition). I will release a new patch by the end of the day.

Here's a MRE with ForwardDiff.jl, ReverseDiff.jl and Mooncake.jl autodiff:

using LinearAlgebra
using Logging
using ModelPredictiveControl
using ReverseDiff
using Mooncake
using ForwardDiff
const ERROR_ONLY = ConsoleLogger(stderr, Logging.Error)

A  = [0.9 0.08; -0.15 0.75]
Bu = [0.005, 0.09]
C  = [1.0 0.0]

# needed for Mooncake, a `@warn` call make it crashes, even in a branch never reached:
Mooncake.@mooncake_overlay ModelPredictiveControl.verify_delays(model, Hp) = nothing 

function first_move(Nwt)
    T = eltype(Nwt)
    model = LinModel{T}(A, Bu, C, 0, 0, 0.1)
    estim = KalmanFilter(model, nint_ym=0, verify_obsv=false)
    mpc = ExplicitMPC(estim; Hp=20, Hc=2, Nwt=Nwt, warn_cond=Inf)
    preparestate!(mpc, [0.0])
    return moveinput!(mpc, [1.0])[1]
end

@show first_move([0.5])

∇f = with_logger(ERROR_ONLY) do # suppress the `verify_delays` warning:
    ForwardDiff.gradient(first_move, [0.5])
end
@show ∇f
∇f = with_logger(ERROR_ONLY) do # suppress the `verify_delays` warning:
    ReverseDiff.gradient(first_move, [0.5])
end
@show ∇f
cache = Mooncake.prepare_gradient_cache(first_move, [0.5])
f, ∇f = Mooncake.value_and_gradient!!(cache, first_move, [0.5])
@show ∇f[2]

printing:

first_move([0.5]) = 2.0023741965935966
∇f = [-1.5058894886897187]
∇f = [-1.5058894886897185]
∇f[2] = [-1.5058894886897192]

@franckgaga

Copy link
Copy Markdown
Member Author

I will close the issue, I won't put too much time on Enzyme, a bit too finicky and I was not able to make it work.

Closes #523

@codecov-commenter

codecov-commenter commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.50%. Comparing base (dd67ee0) to head (a7346af).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #529      +/-   ##
==========================================
+ Coverage   97.30%   97.50%   +0.19%     
==========================================
  Files          28       28              
  Lines        7099     7094       -5     
==========================================
+ Hits         6908     6917       +9     
+ Misses        191      177      -14     
Flag Coverage Δ
unittests 97.50% <100.00%> (+0.19%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@PTWaade

PTWaade commented Nov 25, 2026

Copy link
Copy Markdown

Thank you @franckgaga - this is very exciting !
Yeah I think an upstream Enzyme problem would need to be solved first; don't worry about that. If it ever becomes crucial, I can try and help out with it, but Mooncake, Forward and Reverse is already incredible!

Thank you very much ! I'll get back to you :)

With gratitude and excitwment,
Peter

They are useless, on a second thought. The exception thrown in `ModelPredictiveControl.inv!` and the associated stacktrace is already clear enough.
Testing covariance matrices with non-zero off-diagonal coefficients.
@franckgaga franckgaga changed the title added: ExplicitMPC now support AD with Mooncake.jl + warn_cond kw arg added: ExplicitMPC now support AD with Mooncake.jl + warn_cond kwarg Nov 25, 2026
@franckgaga
franckgaga merged commit de351a0 into main Nov 25, 2026
14 of 15 checks passed
@franckgaga
franckgaga deleted the weight_cov branch November 25, 2026 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Building an ExplicitMPC from dual numbers fails in eigenvalue checks, so its weights can't be differentiated

3 participants