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

Improve numerical stability of normal quantile gradients #3139

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Update vectorisation
andrjohns committed Jan 13, 2025
commit b713e5808feaf6702350631760d094a46929a4fc
13 changes: 7 additions & 6 deletions stan/math/rev/prob/std_normal_log_qf.hpp
Original file line number Diff line number Diff line change
@@ -4,7 +4,8 @@
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/prob/std_normal_log_qf.hpp>
#include <stan/math/prim/functor/apply_scalar_ternary.hpp>
#include <stan/math/prim/functor/apply_scalar_binary.hpp>
#include <stan/math/prim/fun/elt_multiply.hpp>
#include <cmath>

namespace stan {
@@ -20,11 +21,11 @@ template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inline auto std_normal_log_qf(const var_value<T>& log_p) {
const auto& arena_rtn = to_arena(std_normal_log_qf(log_p.val()));
return make_callback_var(arena_rtn, [log_p, arena_rtn](auto& vi) mutable {
log_p.adj() += apply_scalar_ternary(
[](const auto& adj, const auto& logp_val, const auto& rtn_val) {
return adj * exp(logp_val - std_normal_lpdf(rtn_val));
},
vi.adj(), log_p.val(), arena_rtn.val());
auto deriv = apply_scalar_binary(log_p.val(), arena_rtn,
[](const auto& logp_val, const auto& rtn_val) {
return exp(logp_val - std_normal_lpdf(rtn_val));
});
log_p.adj() += elt_multiply(vi.adj(), deriv);
});
}