Skip to content

Commit afb5c44

Browse files
authored
Add check_model argument to optimisation (#2518)
1 parent e4cd6a2 commit afb5c44

File tree

4 files changed

+21
-1
lines changed

4 files changed

+21
-1
lines changed

HISTORY.md

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
# Release 0.37.1
2+
3+
`maximum_a_posteriori` and `maximum_likelihood` now perform sanity checks on the model before running the optimisation.
4+
To disable this, set the keyword argument `check_model=false`.
5+
16
# Release 0.37.0
27

38
## Breaking changes

Project.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "Turing"
22
uuid = "fce5fe82-541a-59a6-adf8-730c64b5f9a0"
3-
version = "0.37.0"
3+
version = "0.37.1"
44

55
[deps]
66
ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b"

src/optimisation/Optimisation.jl

+5
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,8 @@ Under the hood this function calls `Optimization.solve`.
525525
if non-box constraints are present.
526526
527527
# Keyword arguments
528+
- `check_model::Bool=true`: If true, the model is checked for errors before
529+
optimisation begins.
528530
- `initial_params::Union{AbstractVector,Nothing}=nothing`: Initial value for the
529531
optimization. Optional, unless non-box constraints are specified. If omitted it is
530532
generated by either sampling from the prior distribution or uniformly from the box
@@ -538,6 +540,7 @@ function estimate_mode(
538540
model::DynamicPPL.Model,
539541
estimator::ModeEstimator,
540542
solver=nothing;
543+
check_model::Bool=true,
541544
initial_params=nothing,
542545
adtype=ADTypes.AutoForwardDiff(),
543546
cons=nothing,
@@ -547,6 +550,8 @@ function estimate_mode(
547550
ub=nothing,
548551
kwargs...,
549552
)
553+
check_model && DynamicPPL.check_model(model; error_on_failure=true)
554+
550555
constraints = ModeEstimationConstraints(lb, ub, cons, lcons, ucons)
551556
initial_params = generate_initial_params(model, initial_params, constraints)
552557
if solver === nothing

test/optimisation/Optimisation.jl

+10
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,16 @@ using Turing
115115
end
116116
end
117117

118+
@testset "errors on invalid model" begin
119+
@model function invalid_model()
120+
x ~ Normal()
121+
return x ~ Beta()
122+
end
123+
m = invalid_model()
124+
@test_throws ErrorException maximum_likelihood(m)
125+
@test_throws ErrorException maximum_a_posteriori(m)
126+
end
127+
118128
@testset "gdemo" begin
119129
"""
120130
check_success(result, true_value, true_logp, check_retcode=true)

0 commit comments

Comments
 (0)