Skip to content

Fix #3041: Add tuple support to reduce_sum autodiff helpers#3300

Draft
nsiccha wants to merge 9 commits intostan-dev:developfrom
nsiccha:fix/3041-map-tuple
Draft

Fix #3041: Add tuple support to reduce_sum autodiff helpers#3300
nsiccha wants to merge 9 commits intostan-dev:developfrom
nsiccha:fix/3041-map-tuple

Conversation

@nsiccha
Copy link
Copy Markdown

@nsiccha nsiccha commented Mar 25, 2026

I'll check the changes before marking it as ready for review.

Human content above


Claude content below

Problem

When STAN_THREADS=true, reduce_sum with tuple arguments fails to compile because three internal autodiff helper functions — deep_copy_vars, save_varis, and accumulate_adjoints — have overloads for var, std::vector, and Eigen types but not std::tuple. This prevents using tuples to pass mixed parameter/data arguments to reduce_sum in threaded mode.

Change

Three files in stan/math/rev/core/, each gets a tuple overload that unpacks the tuple via stan::math::apply and recursively processes each element:

  1. deep_copy_vars.hppdeep_copy_vars(Tuple&&): deep-copies var elements, forwards non-var elements unchanged. Includes apply.hpp.
  2. save_varis.hppsave_varis(vari**, Tuple&&, Pargs&&...): unpacks tuple and saves vari pointers from each element. Includes apply.hpp. Forward declaration added.
  3. accumulate_adjoints.hppaccumulate_adjoints(double*, Tuple&&, Pargs&&...): unpacks tuple and accumulates adjoints from each element. Includes apply.hpp. Forward declaration added.

Tests added to all three existing test files covering tuple<var, int>, tuple<var, double>, and tuple<var, var>.

MWE

Stan model using reduce_sum with tuple(real, int) parameter (mixing a parameter mu with data K), compiled via BridgeStan with STAN_THREADS=true and MATH= pointing to the patched math library. Verifies log density and gradients are finite and consistent. Fails on main (compilation error in save_varis/deep_copy_vars), passes on worktree.

MWE

Note: MWE scripts are committed to the mwe/ directory on this branch but are removed in the final commit (so they won't be included after squash merge). To run them locally, check out the penultimate commit: git checkout HEAD~1 -- mwe/

mwe.jl

using BridgeStan

stan_code = """
functions {
  real partial_sum(array[] real slice, int start, int end,
                   tuple(real, int) params) {
    real mu = params.1;
    int K = params.2;
    real lp = 0;
    for (i in 1:size(slice)) {
      lp += normal_lpdf(slice[i] | mu, K);
    }
    return lp;
  }
}
data {
  int N;
  int K;
  array[N] real y;
}
parameters {
  real mu;
}
model {
  mu ~ normal(0, 10);
  target += reduce_sum(partial_sum, y, 1, (mu, K));
}
"""

stan_math = ENV["MWE_RUN_DIR"]
label = ENV["MWE_LABEL"]

workdir = mktempdir()
stan_file = joinpath(workdir, "mwe.stan")
write(stan_file, stan_code)

lib = compile_model(stan_file; make_args=["MATH=$stan_math/", "STAN_THREADS=true"])

data = """{"N": 5, "K": 2, "y": [1.0, 2.0, 3.0, 4.0, 5.0]}"""
sm = StanModel(lib, data)

params = [3.0]  # mu (unconstrained)
lp = log_density(sm, params)
lp_grad, grad = log_density_gradient(sm, params)

println("[$label] log_density = $lp")
println("[$label] gradient = $grad")

@assert isfinite(lp) "log_density should be finite"
@assert all(isfinite, grad) "gradient should be finite"
@assert lp  lp_grad "log_density values should match"
@assert length(grad) == 1 "gradient should have 1 element"

println("[$label] All checks passed!")

main output:

# Restarting MWE...
��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ERROR: LoadError: Compilation failed!
Command: setenv(`make MATH=/home/niko/github/stan-dev/math/ STAN_THREADS=true /tmp/jl_X7qkPS/mwe_model.so`; dir="/home/niko/.bridgestan/bridgestan-2.7.0")
stdout: 
--- Translating Stan model to C++ code ---
./bin/stanc  --o=/tmp/jl_X7qkPS/mwe.hpp /tmp/jl_X7qkPS/mwe.stan

--- Compiling C++ code ---
g++ -std=c++17 -pthread -D_REENTRANT -Wno-sign-compare -Wno-ignored-attributes -Wno-class-memaccess     -DSTAN_THREADS -I /home/niko/github/stan-dev/math/lib/tbb_2020.3/include    -O3 -I ./stan/src -I ./stan/lib/rapidjson_1.1.0/ -I /home/niko/github/stan-dev/math/ -I /home/niko/github/stan-dev/math/lib/eigen_3.4.0 -I /home/niko/github/stan-dev/math/lib/boost_1.87.0 -I /home/niko/github/stan-dev/math/lib/sundials_6.1.1/include -I /home/niko/github/stan-dev/math/lib/sundials_6.1.1/src/sundials -fPIC -fvisibility=hidden -fvisibility-inlines-hidden    -DBOOST_DISABLE_ASSERTS         -DBRIDGESTAN_EXPORT -DSTAN_OVERRIDE_EIGEN_ASSERT  -c  -x c++ -o /tmp/jl_X7qkPS/mwe.o /tmp/jl_X7qkPS/mwe.hpp
rm /tmp/jl_X7qkPS/mwe.hpp

stderr: In file included from /home/niko/github/stan-dev/math/stan/math/rev/functor.hpp:30,
                 from /home/niko/github/stan-dev/math/stan/math/rev.hpp:15,
                 from /home/niko/github/stan-dev/math/stan/math.hpp:19,
                 from ./stan/src/stan/model/model_header.hpp:6,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp: In instantiation of ‘stan::math::var stan::math::internal::reduce_sum_impl<ReduceFunction, typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type, ReturnType, Vec, Args ...>::operator()(Vec&&, bool, int, std::ostream*, Args&& ...) const [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; ReturnType = stan::math::var_value<double>; Vec = const std::vector<double>&; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type = void; typename std::decay<_Tp2>::type = std::decay<stan::math::var_value<double> >::type; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’:
/home/niko/github/stan-dev/math/stan/math/prim/functor/reduce_sum.hpp:208:60:   required from ‘auto stan::math::reduce_sum(Vec&&, int, std::ostream*, Args&& ...) [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; Vec = const std::vector<double>&; <template-parameter-1-3> = void; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:252:71:   required from ‘stan::scalar_type_t<T2> mwe_model_namespace::mwe_model::log_prob_impl(VecR&, VecI&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; VecR = Eigen::Matrix<stan::math::var_value<double>, -1, 1>; VecI = Eigen::Matrix<int, -1, 1>; stan::require_vector_like_t<VecR>* <anonymous> = 0; stan::require_vector_like_vt<std::is_integral, VecI>* <anonymous> = 0; stan::require_st_var<VecR>* <anonymous> = 0; stan::scalar_type_t<T2> = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:434:47:   required from ‘T_ mwe_model_namespace::mwe_model::log_prob(Eigen::Matrix<T_a, -1, 1>&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; T_ = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:98:72:   required from ‘stan::math::var stan::model::model_base_crtp<M>::log_prob(Eigen::Matrix<stan::math::var_value<double>, -1, 1>&, std::ostream*) const [with M = mwe_model_namespace::mwe_model; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:96:20:   required from here
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:241:15: error: no matching function for call to ‘save_varis(stan::math::vari**, std::tuple<stan::math::var_value<double, void>&, const int&>&)’
  241 |     save_varis(varis + num_vars_sliced_terms, args...);
      |     ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/core.hpp:79,
                 from ./stan/src/stan/model/model_base.hpp:8,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:51:15: note: candidate: ‘template<class ... Pargs> stan::math::vari** stan::math::save_varis(stan::math::vari**, const var&, Pargs&& ...)’
   51 | inline vari** save_varis(vari** dest, const var& x, Pargs&&... args) {
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:51:15: note:   template argument deduction/substitution failed:
In file included from /home/niko/github/stan-dev/math/stan/math/rev/functor.hpp:30,
                 from /home/niko/github/stan-dev/math/stan/math/rev.hpp:15,
                 from /home/niko/github/stan-dev/math/stan/math.hpp:19,
                 from ./stan/src/stan/model/model_header.hpp:6,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:241:15: note:   cannot convert ‘args#0’ (type ‘std::tuple<stan::math::var_value<double, void>&, const int&>’) to type ‘const var&’ {aka ‘const stan::math::var_value<double>&’}
  241 |     save_varis(varis + num_vars_sliced_terms, args...);
      |     ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/core.hpp:79,
                 from ./stan/src/stan/model/model_base.hpp:8,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:71:15: note: candidate: ‘template<class VarVec, stan::require_std_vector_vt<stan::is_var, VarVec>* <anonymous>, class ... Pargs> stan::math::vari** stan::math::save_varis(stan::math::vari**, VarVec&&, Pargs&& ...)’
   71 | inline vari** save_varis(vari** dest, VarVec&& x, Pargs&&... args) {
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:71:15: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/11/bits/move.h:57,
                 from /usr/include/c++/11/bits/exception_ptr.h:43,
                 from /usr/include/c++/11/exception:153,
                 from /usr/include/c++/11/ios:39,
                 from /usr/include/c++/11/istream:38,
                 from /usr/include/c++/11/sstream:38,
                 from ./stan/src/stan/io/var_context.hpp:4,
                 from ./stan/src/stan/model/model_base.hpp:7,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/usr/include/c++/11/type_traits: In substitution of ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = false; _Tp = void]’:
/home/niko/github/stan-dev/math/stan/math/prim/meta/require_helpers.hpp:19:7:   required by substitution of ‘template<class Check> using require_t = std::enable_if_t<Check::value> [with Check = std::integral_constant<bool, false>]’
/home/niko/github/stan-dev/math/stan/math/prim/meta/is_vector.hpp:677:7:   required by substitution of ‘template<template<class ...> class TypeCheck, class ... Check> using require_std_vector_vt = stan::require_t<stan::container_type_check_base<stan::is_std_vector, stan::value_type_t, TypeCheck, Check ...> > [with TypeCheck = stan::is_var; Check = {std::tuple<stan::math::var_value<double, void>&, const int&>&}]’
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:18:69:   required from ‘stan::math::var stan::math::internal::reduce_sum_impl<ReduceFunction, typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type, ReturnType, Vec, Args ...>::operator()(Vec&&, bool, int, std::ostream*, Args&& ...) const [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; ReturnType = stan::math::var_value<double>; Vec = const std::vector<double>&; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type = void; typename std::decay<_Tp2>::type = std::decay<stan::math::var_value<double> >::type; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/home/niko/github/stan-dev/math/stan/math/prim/functor/reduce_sum.hpp:208:60:   required from ‘auto stan::math::reduce_sum(Vec&&, int, std::ostream*, Args&& ...) [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; Vec = const std::vector<double>&; <template-parameter-1-3> = void; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:252:71:   required from ‘stan::scalar_type_t<T2> mwe_model_namespace::mwe_model::log_prob_impl(VecR&, VecI&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; VecR = Eigen::Matrix<stan::math::var_value<double>, -1, 1>; VecI = Eigen::Matrix<int, -1, 1>; stan::require_vector_like_t<VecR>* <anonymous> = 0; stan::require_vector_like_vt<std::is_integral, VecI>* <anonymous> = 0; stan::require_st_var<VecR>* <anonymous> = 0; stan::scalar_type_t<T2> = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:434:47:   required from ‘T_ mwe_model_namespace::mwe_model::log_prob(Eigen::Matrix<T_a, -1, 1>&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; T_ = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:98:72:   required from ‘stan::math::var stan::model::model_base_crtp<M>::log_prob(Eigen::Matrix<stan::math::var_value<double>, -1, 1>&, std::ostream*) const [with M = mwe_model_namespace::mwe_model; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:96:20:   required from here
/usr/include/c++/11/type_traits:2579:11: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
 2579 |     using enable_if_t = typename enable_if<_Cond, _Tp>::type;
      |           ^~~~~~~~~~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/core.hpp:79,
                 from ./stan/src/stan/model/model_base.hpp:8,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp: In instantiation of ‘stan::math::var stan::math::internal::reduce_sum_impl<ReduceFunction, typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type, ReturnType, Vec, Args ...>::operator()(Vec&&, bool, int, std::ostream*, Args&& ...) const [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; ReturnType = stan::math::var_value<double>; Vec = const std::vector<double>&; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type = void; typename std::decay<_Tp2>::type = std::decay<stan::math::var_value<double> >::type; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’:
/home/niko/github/stan-dev/math/stan/math/prim/functor/reduce_sum.hpp:208:60:   required from ‘auto stan::math::reduce_sum(Vec&&, int, std::ostream*, Args&& ...) [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; Vec = const std::vector<double>&; <template-parameter-1-3> = void; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:252:71:   required from ‘stan::scalar_type_t<T2> mwe_model_namespace::mwe_model::log_prob_impl(VecR&, VecI&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; VecR = Eigen::Matrix<stan::math::var_value<double>, -1, 1>; VecI = Eigen::Matrix<int, -1, 1>; stan::require_vector_like_t<VecR>* <anonymous> = 0; stan::require_vector_like_vt<std::is_integral, VecI>* <anonymous> = 0; stan::require_st_var<VecR>* <anonymous> = 0; stan::scalar_type_t<T2> = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:434:47:   required from ‘T_ mwe_model_namespace::mwe_model::log_prob(Eigen::Matrix<T_a, -1, 1>&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; T_ = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:98:72:   required from ‘stan::math::var stan::model::model_base_crtp<M>::log_prob(Eigen::Matrix<stan::math::var_value<double>, -1, 1>&, std::ostream*) const [with M = mwe_model_namespace::mwe_model; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:96:20:   required from here
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:93:15: note: candidate: ‘template<class VecContainer, stan::require_std_vector_st<stan::is_var, VecContainer>* <anonymous>, stan::require_std_vector_vt<stan::is_container, VecContainer>* <anonymous>, class ... Pargs> stan::math::vari** stan::math::save_varis(stan::math::vari**, VecContainer&&, Pargs&& ...)’
   93 | inline vari** save_varis(vari** dest, VecContainer&& x, Pargs&&... args) {
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:93:15: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:114:15: note: candidate: ‘template<class EigT, stan::require_eigen_vt<stan::is_var, EigT>* <anonymous>, class ... Pargs> stan::math::vari** stan::math::save_varis(stan::math::vari**, EigT&&, Pargs&& ...)’
  114 | inline vari** save_varis(vari** dest, EigT&& x, Pargs&&... args) {
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:114:15: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:135:15: note: candidate: ‘template<class Arith, stan::require_st_arithmetic<Arith>* <anonymous>, class ... Pargs> stan::math::vari** stan::math::save_varis(stan::math::vari**, Arith&&, Pargs&& ...)’
  135 | inline vari** save_varis(vari** dest, Arith&& x, Pargs&&... args) {
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:135:15: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:144:15: note: candidate: ‘stan::math::vari** stan::math::save_varis(stan::math::vari**)’
  144 | inline vari** save_varis(vari** dest) { return dest; }
      |               ^~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/save_varis.hpp:144:15: note:   candidate expects 1 argument, 2 provided
In file included from /home/niko/github/stan-dev/math/stan/math/rev/functor.hpp:30,
                 from /home/niko/github/stan-dev/math/stan/math/rev.hpp:15,
                 from /home/niko/github/stan-dev/math/stan/math.hpp:19,
                 from ./stan/src/stan/model/model_header.hpp:6,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp: In instantiation of ‘struct stan::math::internal::reduce_sum_impl<mwe_model_namespace::partial_sum_rsfunctor__, void, stan::math::var_value<double>, const std::vector<double>&, std::tuple<stan::math::var_value<double, void>&, const int&> >::scoped_args_tuple’:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:58:23:   required from ‘struct stan::math::internal::reduce_sum_impl<mwe_model_namespace::partial_sum_rsfunctor__, void, stan::math::var_value<double>, const std::vector<double>&, std::tuple<stan::math::var_value<double, void>&, const int&> >::recursive_reducer’
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:247:23:   required from ‘stan::math::var stan::math::internal::reduce_sum_impl<ReduceFunction, typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type, ReturnType, Vec, Args ...>::operator()(Vec&&, bool, int, std::ostream*, Args&& ...) const [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; ReturnType = stan::math::var_value<double>; Vec = const std::vector<double>&; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; typename std::enable_if<stan::is_var<typename std::decay<_Tp2>::type>::value, void>::type = void; typename std::decay<_Tp2>::type = std::decay<stan::math::var_value<double> >::type; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/home/niko/github/stan-dev/math/stan/math/prim/functor/reduce_sum.hpp:208:60:   required from ‘auto stan::math::reduce_sum(Vec&&, int, std::ostream*, Args&& ...) [with ReduceFunction = mwe_model_namespace::partial_sum_rsfunctor__; Vec = const std::vector<double>&; <template-parameter-1-3> = void; Args = {std::tuple<stan::math::var_value<double, void>&, const int&>}; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:252:71:   required from ‘stan::scalar_type_t<T2> mwe_model_namespace::mwe_model::log_prob_impl(VecR&, VecI&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; VecR = Eigen::Matrix<stan::math::var_value<double>, -1, 1>; VecI = Eigen::Matrix<int, -1, 1>; stan::require_vector_like_t<VecR>* <anonymous> = 0; stan::require_vector_like_vt<std::is_integral, VecI>* <anonymous> = 0; stan::require_st_var<VecR>* <anonymous> = 0; stan::scalar_type_t<T2> = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
/tmp/jl_X7qkPS/mwe.hpp:434:47:   required from ‘T_ mwe_model_namespace::mwe_model::log_prob(Eigen::Matrix<T_a, -1, 1>&, std::ostream*) const [with bool propto__ = false; bool jacobian__ = false; T_ = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:98:72:   required from ‘stan::math::var stan::model::model_base_crtp<M>::log_prob(Eigen::Matrix<stan::math::var_value<double>, -1, 1>&, std::ostream*) const [with M = mwe_model_namespace::mwe_model; stan::math::var = stan::math::var_value<double>; std::ostream = std::basic_ostream<char>]’
./stan/src/stan/model/model_base_crtp.hpp:96:20:   required from here
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:36:45: error: no matching function for call to ‘deep_copy_vars(std::tuple<stan::math::var_value<double, void>&, const int&>)’
   36 |         = std::tuple<decltype(deep_copy_vars(std::declval<Args>()))...>;
      |                               ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/core.hpp:19,
                 from ./stan/src/stan/model/model_base.hpp:8,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:23:14: note: candidate: ‘template<class Arith, class> Arith stan::math::deep_copy_vars(Arith&&)’
   23 | inline Arith deep_copy_vars(Arith&& arg) {
      |              ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:23:14: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:45:13: note: candidate: ‘template<class VarVec, stan::require_std_vector_vt<stan::is_var, VarVec>* <anonymous> > auto stan::math::deep_copy_vars(VarVec&&)’
   45 | inline auto deep_copy_vars(VarVec&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:45:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:63:13: note: candidate: ‘template<class VecContainer, stan::require_std_vector_st<stan::is_var, VecContainer>* <anonymous>, stan::require_std_vector_vt<stan::is_container, VecContainer>* <anonymous> > auto stan::math::deep_copy_vars(VecContainer&&)’
   63 | inline auto deep_copy_vars(VecContainer&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:63:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:79:13: note: candidate: ‘template<class EigT, stan::require_eigen_vt<stan::is_var, EigT>* <anonymous> > auto stan::math::deep_copy_vars(EigT&&)’
   79 | inline auto deep_copy_vars(EigT&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:79:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:33:13: note: candidate: ‘auto stan::math::deep_copy_vars(const var&)’
   33 | inline auto deep_copy_vars(const var& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:33:39: note:   no known conversion for argument 1 from ‘std::tuple<stan::math::var_value<double, void>&, const int&>’ to ‘const var&’ {aka ‘const stan::math::var_value<double>&’}
   33 | inline auto deep_copy_vars(const var& arg) {
      |                            ~~~~~~~~~~~^~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/functor.hpp:30,
                 from /home/niko/github/stan-dev/math/stan/math/rev.hpp:15,
                 from /home/niko/github/stan-dev/math/stan/math.hpp:19,
                 from ./stan/src/stan/model/model_header.hpp:6,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/functor/reduce_sum.hpp:36:45: error: no matching function for call to ‘deep_copy_vars(std::tuple<stan::math::var_value<double, void>&, const int&>)’
   36 |         = std::tuple<decltype(deep_copy_vars(std::declval<Args>()))...>;
      |                               ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
In file included from /home/niko/github/stan-dev/math/stan/math/rev/core.hpp:19,
                 from ./stan/src/stan/model/model_base.hpp:8,
                 from ./stan/src/stan/model/model_header.hpp:4,
                 from /tmp/jl_X7qkPS/mwe.hpp:2:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:23:14: note: candidate: ‘template<class Arith, class> Arith stan::math::deep_copy_vars(Arith&&)’
   23 | inline Arith deep_copy_vars(Arith&& arg) {
      |              ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:23:14: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:45:13: note: candidate: ‘template<class VarVec, stan::require_std_vector_vt<stan::is_var, VarVec>* <anonymous> > auto stan::math::deep_copy_vars(VarVec&&)’
   45 | inline auto deep_copy_vars(VarVec&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:45:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:63:13: note: candidate: ‘template<class VecContainer, stan::require_std_vector_st<stan::is_var, VecContainer>* <anonymous>, stan::require_std_vector_vt<stan::is_container, VecContainer>* <anonymous> > auto stan::math::deep_copy_vars(VecContainer&&)’
   63 | inline auto deep_copy_vars(VecContainer&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:63:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:79:13: note: candidate: ‘template<class EigT, stan::require_eigen_vt<stan::is_var, EigT>* <anonymous> > auto stan::math::deep_copy_vars(EigT&&)’
   79 | inline auto deep_copy_vars(EigT&& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:79:13: note:   template argument deduction/substitution failed:
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:33:13: note: candidate: ‘auto stan::math::deep_copy_vars(const var&)’
   33 | inline auto deep_copy_vars(const var& arg) {
      |             ^~~~~~~~~~~~~~
/home/niko/github/stan-dev/math/stan/math/rev/core/deep_copy_vars.hpp:33:39: note:   no known conversion for argument 1 from ‘std::tuple<stan::math::var_value<double, void>&, const int&>’ to ‘const var&’ {aka ‘const stan::math::var_value<double>&’}
   33 | inline auto deep_copy_vars(const var& arg) {
      |                            ~~~~~~~~~~~^~~
make: *** [Makefile:77: /tmp/jl_X7qkPS/mwe.o] Error 1

Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] compile_model(stan_file::String; stanc_args::Vector{String}, make_args::Vector{String})
   @ BridgeStan ~/.julia/packages/BridgeStan/Bodre/src/compile.jl:114
 [3] top-level scope
   @ ~/github/issues/stan-dev-math/worktrees/3041-map-tuple/mwe/mwe.jl:37
in expression starting at /home/niko/github/issues/stan-dev-math/worktrees/3041-map-tuple/mwe/mwe.jl:37

# exit_code: 1
# status: FAIL
# finished: 2026-03-25 13:22:02

worktree output:

# Restarting MWE...
�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������==> Running mwe.jl
[worktree] log_density = -9.35542856882309
[worktree] gradient = [-0.030000000000000006]
[worktree] All checks passed!

# exit_code: 0
# status: PASS
# finished: 2026-03-25 13:22:05

Fixes #3041

nsiccha and others added 7 commits March 25, 2026 09:55
Add tuple specialization to apply_scalar_unary so that vectorized
math functions (exp, sin, cos, etc.) automatically work on tuples.
Also extend require_ad_container_t to accept tuples containing
autodiff types, and add is_autodiff support for tuples.

Fixes stan-dev#3041

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
These three functions handle var, vector<var>, Eigen<var>, and arithmetic
types but not tuples. With STAN_THREADS=true, reduce_sum passes tuple
arguments through these functions, causing compilation failures.

Add tuple overloads that unpack the tuple via stan::math::apply and
recursively process each element.

Fixes stan-dev#3041

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Remove unnecessary <tuple> includes (already available via prim/meta.hpp).
Add doxygen comments matching existing style. Add unit tests for
tuple overloads of deep_copy_vars, save_varis, and accumulate_adjoints
covering tuple<var, int>, tuple<var, double>, and tuple<var, var>.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@nsiccha
Copy link
Copy Markdown
Author

nsiccha commented Mar 25, 2026

I'm just gonna @WardBrian: The above PR is 100% Claude generated - don't review it yet please. But is there anything "extra" that I should tell Claude (or also watch out for myself)?

@nsiccha nsiccha force-pushed the fix/3041-map-tuple branch from db5f6de to 3f05bea Compare March 25, 2026 12:32
@WardBrian
Copy link
Copy Markdown
Member

@SteveBronder is probably the better person to ask, both because he has more experience with Claude and because when working on some Laplace stuff he told me he had some code that he thought would help solve this reduce sum issue

@stan-buildbot
Copy link
Copy Markdown
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
gp_regr/gp_regr.stan 0.09 0.09 0.99 -1.03% slower
gp_regr/gen_gp_data.stan 0.02 0.02 1.0 -0.01% slower
arK/arK.stan 1.78 1.74 1.02 2.14% faster
eight_schools/eight_schools.stan 0.05 0.05 0.97 -2.68% slower
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 8.65 8.32 1.04 3.77% faster
pkpd/one_comp_mm_elim_abs.stan 19.0 18.71 1.02 1.51% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.24 0.24 1.0 -0.21% slower
sir/sir.stan 67.67 66.94 1.01 1.08% faster
gp_pois_regr/gp_pois_regr.stan 2.75 2.7 1.02 1.68% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.59 2.61 0.99 -0.54% slower
irt_2pl/irt_2pl.stan 4.03 3.9 1.03 3.21% faster
arma/arma.stan 0.28 0.27 1.04 4.01% faster
garch/garch.stan 0.41 0.4 1.03 2.52% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.0 0.31% faster
performance.compilation 224.47 219.03 1.02 2.43% faster
Mean result: 1.0126233698338922

Jenkins Console Log
Blue Ocean
Commit hash: 240e2dc95a112f175bb961a03b53357d10955996


Machine information No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
Address sizes: 46 bits physical, 48 bits virtual
CPU(s): 80
On-line CPU(s) list: 0-79
Thread(s) per core: 2
Core(s) per socket: 20
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
Stepping: 4
CPU MHz: 2765.158
CPU max MHz: 3700.0000
CPU min MHz: 1000.0000
BogoMIPS: 4800.00
Virtualization: VT-x
L1d cache: 1.3 MiB
L1i cache: 1.3 MiB
L2 cache: 40 MiB
L3 cache: 55 MiB
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2: Mitigation; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Vmscape: Mitigation; IBPB before exit to userspace
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

G++:
g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:
clang version 10.0.0-4ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

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.

reduce_sum fails if tuples are passed

3 participants