Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up var memory in laplace_sample #3324

Merged
merged 2 commits into from
Dec 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions src/stan/services/optimize/laplace_sample.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,10 @@ void laplace_sample(const Model& model, const Eigen::VectorXd& theta_hat,

// create log density functor for vars and vals
std::stringstream log_density_msgs;
auto log_density_fun
= [&](const Eigen::Matrix<stan::math::var, -1, 1>& theta) {
return model.template log_prob<true, jacobian, stan::math::var>(
const_cast<Eigen::Matrix<stan::math::var, -1, 1>&>(theta),
&log_density_msgs);
};
auto log_density_fun = [&](auto&& theta) {
return model.template log_prob<true, jacobian, stan::math::var>(
theta, &log_density_msgs);
};

// calculate inverse negative Hessian's Cholesky factor
if (refresh > 0) {
Expand Down Expand Up @@ -121,7 +119,10 @@ void laplace_sample(const Model& model, const Eigen::VectorXd& theta_hat,

double log_p;
if (calculate_lp) {
log_p = log_density_fun(unc_draw).val();
// clean up created vars after scope exit
stan::math::nested_rev_autodiff stack;
auto theta = unc_draw.cast<stan::math::var>().eval();
log_p = log_density_fun(theta).val();
} else {
log_p = std::numeric_limits<double>::quiet_NaN();
}
Expand Down