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

Closures #2384

Closed
wants to merge 35 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
01f0a03
add closure support and a few tests
nhuurre Feb 19, 2021
7382327
some docs
nhuurre Feb 21, 2021
ee21600
fix headers
nhuurre Feb 21, 2021
a595b43
add from_lambda() for suffix functions, and fix integrate_ode adapter
nhuurre Feb 23, 2021
29c165f
add some minimal docs
nhuurre Mar 6, 2021
5dce92a
Merge branch 'develop' into feature/closures-v2
nhuurre Mar 20, 2021
bbabc92
fix reduce_sum off-by-one index
nhuurre Mar 20, 2021
a4032be
Merge branch 'feature/variadic-integrate-1d' into feature/closures-v2
nhuurre Mar 20, 2021
76a8991
closure support for integrate_1d
nhuurre Mar 20, 2021
a55ddb3
Merge branch 'develop' into feature/closures-v2
nhuurre Apr 20, 2021
990c070
move ode_closure_adapter out of internal namespace
nhuurre Jun 15, 2021
cbf48fa
refactor tests
nhuurre Jun 15, 2021
977f54d
Merge branch 'develop' into feature/closures-v2
nhuurre Jun 15, 2021
c043511
[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.0…
stan-buildbot Jun 15, 2021
e72e6f4
fix cpplint
nhuurre Jun 15, 2021
e120064
fix test
nhuurre Jun 15, 2021
1245fa6
fix promote_scalar_type
nhuurre Jun 15, 2021
9c25817
fix
nhuurre Jun 15, 2021
a749f61
Merge branch 'develop' into feature/closures-v2
nhuurre Jul 14, 2021
6990768
generalize base_closure
nhuurre Jul 19, 2021
2e3180a
non-empty suffix closures
nhuurre Jul 27, 2021
610af2d
cleanup
nhuurre Jul 27, 2021
880e270
remove empty statement
nhuurre Jul 27, 2021
4f1f6eb
fix includes
nhuurre Jul 28, 2021
f883e42
Merge branch 'develop' into feature/closures-v2
nhuurre Jul 28, 2021
75f6d30
missing include
nhuurre Jul 28, 2021
0a609db
fixup names and references logic for closure classes
SteveBronder Aug 10, 2021
e0f6145
remove fn_return_type
SteveBronder Aug 10, 2021
9eca190
Merge commit '02dc560b022f328f917af80a1b9b7f1feb249ee4' into HEAD
yashikno Aug 12, 2021
9436a18
[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.0…
stan-buildbot Aug 12, 2021
2b2bee2
fix headers
SteveBronder Aug 13, 2021
ecec96a
Merge branch 'develop' into feature/closures-v2
nhuurre Sep 7, 2021
03ab504
some docs, a test
nhuurre Sep 7, 2021
9fc569f
Merge branch 'develop' into feature/closures-v2
nhuurre Sep 23, 2021
9fb3740
Merge branch 'develop' into feature/closures-v2
nhuurre Oct 17, 2021
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
7 changes: 7 additions & 0 deletions stan/math/prim/err/elementwise_check.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ inline void elementwise_check(const F& is_good, const char* function,
}();
}
}
template <typename F, typename T, typename... Indexings,
require_stan_closure_t<T>* = nullptr>
inline void elementwise_check(const F& is_good, const char* function,
const char* name, const T& x, const char* must_be,
const Indexings&... indexings) {
// XXX skip closures
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. We'll need to implement these.

Copy link
Member

@bbbales2 bbbales2 Mar 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, thinking more, I don't think there's a big advantage to implementing this.

We could expose the variables captured by a closure to checks, but the Math checks wouldn't know in what order its getting them, and then depending on which function was accepting closures it would need to decide which checks to do on which inputs.

I think instead in the ODE solves we check only the arguments passed in explicitly (which this is effectively doing) or we get rid of the infinity checks on the inputs to the ODE solves. I'll make an issue and see if getting rid of the checks altogether is an option. (Edit: Issue #2406)

}
/**
* Check that the predicate holds for all elements of the value of `x`. This
* overload works on Eigen types that support linear indexing.
Expand Down
13 changes: 13 additions & 0 deletions stan/math/prim/fun/value_of.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,19 @@ inline auto value_of(EigMat&& M) {
std::forward<EigMat>(M));
}

/**
* Closures that capture non-arithmetic types have value_of__() method.
*
* @tparam F Input element type
* @param[in] f Input closure
* @return closure
**/
template <typename F, require_stan_closure_t<F>* = nullptr,
require_not_st_arithmetic<F>* = nullptr>
inline auto value_of(const F& f) {
return f.value_of__();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wow I vaguely remember this. Is this used anywhere yet?

}

} // namespace math
} // namespace stan

Expand Down
1 change: 1 addition & 0 deletions stan/math/prim/functor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <stan/math/prim/functor/apply_scalar_binary.hpp>
#include <stan/math/prim/functor/apply_vector_unary.hpp>
#include <stan/math/prim/functor/coupled_ode_system.hpp>
#include <stan/math/prim/functor/closure_adapter.hpp>
#include <stan/math/prim/functor/finite_diff_gradient.hpp>
#include <stan/math/prim/functor/finite_diff_gradient_auto.hpp>
#include <stan/math/prim/functor/for_each.hpp>
Expand Down
231 changes: 231 additions & 0 deletions stan/math/prim/functor/closure_adapter.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
#ifndef STAN_MATH_PRIM_FUNCTOR_CLOSURE_ADAPTER_HPP
#define STAN_MATH_PRIM_FUNCTOR_CLOSURE_ADAPTER_HPP

#include <stan/math/prim/meta/is_stan_closure.hpp>
#include <stan/math/prim/meta/return_type.hpp>
#include <ostream>

namespace stan {
namespace math {

template <typename F>
struct empty_closure {
using captured_scalar_t__ = double;
using ValueOf__ = empty_closure<F>;
using CopyOf__ = empty_closure<F>;
F f_;

explicit empty_closure(const F& f) : f_(f) {}

template <typename... Args>
auto operator()(std::ostream* msgs, Args... args) const {
return f_(args..., msgs);
}
size_t count_vars__() const { return 0; }
auto value_of__() const { return ValueOf__(f_); }
auto copy_of__() const { return CopyOf__(f_); }
auto deep_copy_vars__() const { return CopyOf__(f_); }
void zero_adjoints__() const {}
double* accumulate_adjoints__(double* dest) const { return dest; }
template <typename Vari>
Vari** save_varis(Vari** dest) const {
return dest;
}
};

template <bool Ref, typename F, typename T>
struct one_arg_closure {
using captured_scalar_t__ = return_type_t<T>;
using ValueOf__
= one_arg_closure<false, F, decltype(value_of(std::declval<T>()))>;
using CopyOf__ = one_arg_closure<false, F, T>;
F f_;
capture_type_t<T, Ref> s_;

explicit one_arg_closure(const F& f, const T& s) : f_(f), s_(s) {}

template <typename... Args>
auto operator()(std::ostream* msgs, Args... args) const {
return f_(s_, args..., msgs);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having functions where the variadic arguments aren't last makes writing the C++ painful (cause no type deduction). Could it go captured_args..., msgs, args...?

}
size_t count_vars__() const { return count_vars(s_); }
auto value_of__() const { return ValueOf__(f_, value_of(s_)); }
auto copy_of__() const { return CopyOf__(f_, s_); }
auto deep_copy_vars__() const { return CopyOf__(f_, deep_copy_vars(s_)); }
void zero_adjoints__() { zero_adjoints(s_); }
double* accumulate_adjoints__(double* dest) const {
return accumulate_adjoints(dest, s_);
}
template <typename Vari>
Vari** save_varis__(Vari** dest) const {
return save_varis(dest, s_);
}
};

template <typename F>
struct empty_closure_rng {
using captured_scalar_t__ = double;
using ValueOf__ = empty_closure_rng<F>;
using CopyOf__ = empty_closure_rng<F>;
F f_;

explicit empty_closure_rng(const F& f) : f_(f) {}

template <typename Rng, typename... Args>
auto operator()(const Rng& rng, std::ostream* msgs, Args... args) const {
return f_(args..., rng, msgs);
}
size_t count_vars__() const { return 0; }
auto value_of__() const { return ValueOf__(f_); }
auto copy_of__() const { return CopyOf__(f_); }
auto deep_copy_vars__() const { return CopyOf__(f_); }
void zero_adjoints__() const {}
double* accumulate_adjoints__(double* dest) const { return dest; }
template <typename Vari>
Vari** save_varis(Vari** dest) const {
return dest;
}
};

template <typename F>
struct empty_closure_lpdf {
using captured_scalar_t__ = double;
using ValueOf__ = empty_closure_lpdf<F>;
using CopyOf__ = empty_closure_lpdf<F>;
F f_;

explicit empty_closure_lpdf(const F& f) : f_(f) {}

template <bool propto = false, typename... Args>
auto operator()(std::ostream* msgs, Args... args) const {
return f_.template operator()<propto>(args..., msgs);
}
size_t count_vars__() const { return 0; }
auto value_of__() const { return ValueOf__(f_); }
auto copy_of__() const { return CopyOf__(f_); }
auto deep_copy_vars__() const { return CopyOf__(f_); }
void zero_adjoints__() const {}
double* accumulate_adjoints__(double* dest) const { return dest; }
template <typename Vari>
Vari** save_varis(Vari** dest) const {
return dest;
}
};

template <typename F>
struct empty_closure_lp {
using captured_scalar_t__ = double;
using ValueOf__ = empty_closure_lp<F>;
using CopyOf__ = empty_closure_lp<F>;
static const size_t vars_count__ = 0;
F f_;

explicit empty_closure_lp(const F& f) : f_(f) {}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
explicit empty_closure_lp(const F& f) : f_(f) {}
template <typename FF>
explicit empty_closure_lp(FF&& f) : f_(std::forward<FF>(f)) {}


template <typename T_lp, typename T_lp_accum, typename... Args>
auto operator()(T_lp_accum& lp, T_lp& lp_accum, std::ostream* msgs,
Args... args) const {
return f_(args..., lp, lp_accum, msgs);
}
size_t count_vars__() const { return 0; }
auto value_of__() const { return ValueOf__(f_); }
auto copy_of__() const { return CopyOf__(f_); }
auto deep_copy_vars__() const { return CopyOf__(f_); }
void zero_adjoints__() const {}
double* accumulate_adjoints__(double* dest) const { return dest; }
template <typename Vari>
Vari** save_varis(Vari** dest) const {
return dest;
}
};

/**
* Create a closure object from a callable.
*/
template <typename F>
auto from_lambda(const F& f) {
return empty_closure<F>(f);
}

/**
* Create a closure that captures a single argument.
*/
template <typename F, typename T>
auto from_lambda(const F& f, const T& a) {
return one_arg_closure<true, F, T>(f, a);
}

template <typename F>
auto rng_from_lambda(const F& f) {
return empty_closure_rng<F>(f);
}

template <typename F>
auto lpdf_from_lambda(const F& f) {
return empty_closure_lpdf<F>(f);
}

template <typename F>
auto lp_from_lambda(const F& f) {
return empty_closure_lp<F>(f);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So for each kind of function we might have in Stan, we can also have a closure version of that.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each function kind follows a different calling convention so each kind needs its own adapter closure. These aren't used in math library but stanc3 allows userdefined higher order functions that might need them.


template <bool Propto, typename F, bool Ref>
struct lpdf_wrapper {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is lpdf_wrapper used for?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So you know how one can do

real func_lpdf(real[] slice, ...) {
  ...
}
target += reduce_sum(func_lpdf, ...);
target += reduce_sum(func_lupdf, ...);

and both reduce_sum calls take the same closure object as the first argument so you should be asking yourself, how does the closure remember if it's lpdf or lupdf?
The answer is that it's wrapped in lpdf_wrapper right before calling reduce_sum. Propto=true means lupdf and Propto=false means lpdf.

using captured_scalar_t__ = return_type_t<F>;
using ValueOf__
= lpdf_wrapper<Propto, decltype(std::declval<F>().value_of__()), false>;
using CopyOf__
= lpdf_wrapper<Propto, decltype(std::declval<F>().copy_of__()), false>;
capture_type_t<F, Ref> f_;

explicit lpdf_wrapper(const F& f) : f_(f) {}

template <bool propto>
auto with_propto() {
return lpdf_wrapper < Propto && propto, F, true > (f_);
}

template <bool propto = Propto, typename... Args>
auto operator()(Args... args) const {
return f_.template operator() < Propto && propto > (args...);
}
size_t count_vars__() const { return count_vars(f_); }
auto value_of__() const { return ValueOf__(value_of(f_)); }
auto deep_copy_vars__() const { return CopyOf__(deep_copy_vars(f_)); }
auto copy_of__() const { return CopyOf__(f_.copy_of__()); }
void zero_adjoints__() { zero_adjoints(f_); }
double* accumulate_adjoints__(double* dest) const {
return accumulate_adjoints(dest, f_);
}
template <typename Vari>
Vari** save_varis__(Vari** dest) const {
return save_varis(dest, f_);
}
};

struct reduce_sum_closure_adapter {
template <typename F, typename T, typename... Args>
auto operator()(const std::vector<T>& sub_slice, std::size_t start,
std::size_t end, std::ostream* msgs, const F& f,
Args... args) const {
return f(msgs, sub_slice, start, end, args...);
}
};

namespace internal {

struct ode_closure_adapter {
template <typename F, typename T0, typename T1, typename... Args>
auto operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
std::ostream* msgs, const F& f, Args... args) const {
return f(msgs, t, y, args...);
}
};

} // namespace internal

} // namespace math
} // namespace stan

#endif
2 changes: 1 addition & 1 deletion stan/math/prim/functor/integrate_ode_rk45.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ inline auto integrate_ode_rk45(
ts, relative_tolerance, absolute_tolerance,
max_num_steps, msgs, theta, x, x_int);

std::vector<std::vector<return_type_t<T_y0, T_param, T_t0, T_ts>>>
std::vector<std::vector<fn_return_type_t<F, T_y0, T_param, T_t0, T_ts>>>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we just have the logic in return_type_t for handling closures?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. I did have some logic for handling closures in return_type_t but for backwards compatibility some places need logic for also handling arbitrary C++ lambdas. I created fn_return_type_t because I wasn't sure if adding a catchall case for "anything that isn't a known type" would have some undesirable side effects. Your branch seems to have resolved that issue.

y_converted;
y_converted.reserve(y.size());
for (size_t i = 0; i < y.size(); ++i)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef STAN_MATH_PRIM_FUNCTOR_INTEGRATE_ODE_STD_VECTOR_INTERFACE_ADAPTER_HPP
#define STAN_MATH_PRIM_FUNCTOR_INTEGRATE_ODE_STD_VECTOR_INTERFACE_ADAPTER_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/to_array_1d.hpp>
#include <stan/math/prim/fun/to_vector.hpp>
#include <ostream>
Expand All @@ -19,11 +20,14 @@ namespace internal {
* state as an Eigen::Matrix. The adapter converts to and from these forms
* so that the old ODE interfaces can work.
*/
template <typename F>
struct integrate_ode_std_vector_interface_adapter {
const F f_;
template <bool is_closure, typename F, bool Ref>
struct integrate_ode_std_vector_interface_adapter_impl;

explicit integrate_ode_std_vector_interface_adapter(const F& f) : f_(f) {}
template <typename F, bool Ref>
struct integrate_ode_std_vector_interface_adapter_impl<false, F, Ref> {
const F& f_;
explicit integrate_ode_std_vector_interface_adapter_impl(const F& f)
: f_(f) {}

template <typename T0, typename T1, typename T2>
auto operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
Expand All @@ -34,6 +38,44 @@ struct integrate_ode_std_vector_interface_adapter {
}
};

template <typename F, bool Ref>
struct integrate_ode_std_vector_interface_adapter_impl<true, F, Ref> {
using captured_scalar_t__ = typename F::captured_scalar_t__;
using ValueOf__ = integrate_ode_std_vector_interface_adapter_impl<
true, typename F::ValueOf__, false>;
using CopyOf__ = integrate_ode_std_vector_interface_adapter_impl<
true, typename F::CopyOf__, false>;
capture_type_t<F, Ref> f_;

explicit integrate_ode_std_vector_interface_adapter_impl(const F& f)
: f_(f) {}

template <typename T0, typename T1, typename T2>
auto operator()(std::ostream* msgs, const T0& t,
const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y,
const std::vector<T2>& theta, const std::vector<double>& x,
const std::vector<int>& x_int) const {
return to_vector(f_(msgs, t, to_array_1d(y), theta, x, x_int));
}

size_t count_vars__() const { return f_.count_vars__(); }
auto value_of__() const { return ValueOf__(f_.value_of__()); }
auto deep_copy_vars__() const { return CopyOf__(f_.deep_copy_vars__()); }
void zero_adjoints__() { f_.zero_adjoints__(); }
double* accumulate_adjoints__(double* dest) const {
return f_.accumulate_adjoints__(dest);
}
template <typename Vari>
Vari** save_varis__(Vari** dest) const {
return f_.save_varis__(dest);
}
};

template <typename F>
using integrate_ode_std_vector_interface_adapter
= integrate_ode_std_vector_interface_adapter_impl<is_stan_closure<F>::value,
F, true>;

} // namespace internal

} // namespace math
Expand Down
Loading