Skip to content

Use Perfect Forwarding in all functions that use apply family of functors #3221

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

Open
wants to merge 26 commits into
base: develop
Choose a base branch
from

Conversation

SteveBronder
Copy link
Collaborator

Summary

This fixes #3208 by using perfect forwarding for all functions that use our underlying apply family of functions for calling functions on containers and containers and containers. The issue was that the Holder class, when used in the apply functors, did not have enough type information to know which arguments it should take ownership of.

Consider the following function, where all types are passed in via constant reference.

template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>
inline auto gamma_p(const T1& a, const T2& b) {
  return apply_scalar_binary(
      [](const auto& c, const auto& d) { return gamma_p(c, d); }, a, b);
}

Calling this function with an Eigen expression that has a temporary in it would not give apply_scalar_binary and the Holder inside of apply_scalar_binary enough information to know that the Holder class should own any of the input arguments. As an example we can look at a simplified version of the code used in poisson_lccdf.hpp.

auto log_Pi = log(gamma_p(n_val + 1.0, lambda_val)));
double log_sum = sum(log_Pi);

gamma_p uses apply_scalar_binary and log uses apply_scalar_unary. We need to make sure the inputs and results of the gamma_p function do not fall out of scope by the time we go through log and then assign to log_Pi. Before this PR it would be possible for the expression n_val + 1.0 to fall out of scope as well as the result of gamma_p to go out of scope from log after log_Pi is assigned.

To combat this we now use perfect forwarding for all of the functions that use our internal apply family of functors. This should allow the Holder used internally by the apply functors to know which types need to be owned by it to make sure things do not fall out of scope.

Tests

There is no new tests for this. Since it is an isue on gcc I do wonder how we should test this in our CI/CD?

Side Effects

I'd like to think of some test we can write so that, in the future, developers do not accidentally write functions that use the apply family of functors that do not use perfect forwarding.

Release notes

Adds perfect forwarding to all functions that use the apply family of functors.

Checklist

  • Copyright holder: Steve Bronder

    The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
    - Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
    - Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

  • the basic tests are passing

    • unit tests pass (to run, use: ./runTests.py test/unit)
    • header checks pass, (make test-headers)
    • dependencies checks pass, (make test-math-dependencies)
    • docs build, (make doxygen)
    • code passes the built in C++ standards checks (make cpplint)
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

@WardBrian
Copy link
Member

@SteveBronder anything I can do to help this over the line?

@SteveBronder
Copy link
Collaborator Author

Right now it is just making sure the tests pass. I think I got it so we should be good!

Copy link
Member

@WardBrian WardBrian left a comment

Choose a reason for hiding this comment

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

Gonna leave the proper review to @andrjohns, just two things that stood out

@@ -17,6 +17,7 @@ namespace math {
template <typename ValueType>
class complex_base {
public:
auto __rep() const { return *this; }
Copy link
Member

Choose a reason for hiding this comment

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

I can't figure out from searching what this would do

@WardBrian
Copy link
Member

Math pipeline looks good, upstream has some (I believe legitimate) failures. All seem to blame trigamma in some way or another


--- Compiling C++ code ---
clang++-6.0 -std=c++17 -D_REENTRANT -Wno-sign-compare -Wno-ignored-attributes      -I stan/lib/stan_math/lib/tbb_2020.3/include    -O0 -I src -I stan/src -I stan/lib/rapidjson_1.1.0/ -I lib/CLI11-1.9.1/ -I stan/lib/stan_math/ -I stan/lib/stan_math/lib/eigen_3.4.0 -I stan/lib/stan_math/lib/boost_1.87.0 -I stan/lib/stan_math/lib/sundials_6.1.1/include -I stan/lib/stan_math/lib/sundials_6.1.1/src/sundials    -DBOOST_DISABLE_ASSERTS          -c -include-pch stan/src/stan/model/model_header.hpp.gch/model_header_4_2.hpp.gch -x c++ -o ../stanc3/test/integration/good/stanc_helper.o ../stanc3/test/integration/good/stanc_helper.hpp
In file included from ../stanc3/test/integration/good/int_overloads.hpp:1:
In file included from stan/src/stan/model/model_header.hpp:6:
In file included from /home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math.hpp:19:
In file included from /home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/rev.hpp:11:
In file included from /home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/rev/constraint.hpp:24:
In file included from /home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/prim/constraint.hpp:4:
In file included from /home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/prim/fun.hpp:335:
/home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/prim/fun/trigamma.hpp:142:12: error: function 'trigamma<stan::math::var_value<double, void> &, nullptr>' with deduced return type cannot be used before it is defined
    return trigamma(std::forward<T>(x));
           ^
/home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/rev/functor/apply_scalar_unary.hpp:34:15: note: in instantiation of function template specialization 'stan::math::trigamma_fun::fun<stan::math::var_value<double, void> &>' requested here
    return F::fun(std::forward<T2>(x));
              ^
/home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/prim/fun/trigamma.hpp:159:47: note: in instantiation of function template specialization 'stan::math::apply_scalar_unary<stan::math::trigamma_fun, stan::math::var_value<double, void> &, void>::apply<stan::math::var_value<double, void> &>' requested here
  return apply_scalar_unary<trigamma_fun, T>::apply(std::forward<T>(x));
                                              ^
../stanc3/test/integration/good/int_overloads.hpp:521:44: note: in instantiation of function template specialization 'stan::math::trigamma<stan::math::var_value<double, void> &, nullptr>' requested here
      transformed_param_real = stan::math::trigamma(p_real);
                                           ^
../stanc3/test/integration/good/int_overloads.hpp:811:12: note: in instantiation of function template specialization 'int_overloads_model_namespace::int_overloads_model::log_prob_impl<false, false, Eigen::Matrix<stan::math::var_value<double, void>, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, nullptr, nullptr, nullptr>' requested here
    return log_prob_impl<propto__, jacobian__>(params_r, params_i, pstream);
           ^
/home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/src/stan/model/model_base_crtp.hpp:98:50: note: in instantiation of function template specialization 'int_overloads_model_namespace::int_overloads_model::log_prob<false, false, stan::math::var_value<double, void> >' requested here
    return static_cast<const M*>(this)->template log_prob<false, false>(theta,
                                                 ^
../stanc3/test/integration/good/int_overloads.hpp:129:3: note: in instantiation of member function 'stan::model::model_base_crtp<int_overloads_model_namespace::int_overloads_model>::log_prob' requested here
  ~int_overloads_model() {}
  ^
/home/jenkins/workspace/Stan_Stan_downstream_tests/performance-tests-cmdstan/cmdstan/stan/lib/stan_math/stan/math/prim/fun/trigamma.hpp:158:13: note: 'trigamma<stan::math::var_value<double, void> &, nullptr>' declared here
inline auto trigamma(T&& x) {
            ^
1 error generated.
make: [make/program:77: ../stanc3/test/integration/good/int_overloads.o] Error 1 (ignored)

@SteveBronder
Copy link
Collaborator Author

Yes I missed one requires in trigamma

@stan-buildbot
Copy link
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
arma/arma.stan 0.32 0.31 1.04 4.13% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.12 10.96% faster
gp_regr/gen_gp_data.stan 0.03 0.02 1.08 7.16% faster
gp_regr/gp_regr.stan 0.09 0.09 1.05 4.36% faster
sir/sir.stan 70.61 67.74 1.04 4.06% faster
irt_2pl/irt_2pl.stan 4.26 3.96 1.08 7.08% faster
eight_schools/eight_schools.stan 0.06 0.05 1.04 3.84% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.26 0.24 1.07 6.92% faster
pkpd/one_comp_mm_elim_abs.stan 19.99 19.05 1.05 4.7% faster
garch/garch.stan 0.43 0.4 1.07 6.89% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.83 2.58 1.1 8.73% faster
arK/arK.stan 1.85 1.72 1.08 6.98% faster
gp_pois_regr/gp_pois_regr.stan 2.86 2.69 1.07 6.18% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 8.91 8.41 1.06 5.63% faster
performance.compilation 177.42 182.14 0.97 -2.66% slower
Mean result: 1.061027427604836

Jenkins Console Log
Blue Ocean
Commit hash: 42e76f7fa79cf13a1e09768a622d7c65d3dfc138


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: 2400.000
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
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

@WardBrian
Copy link
Member

It looks like inv_gamma_00000_generated_vv_test and chi_square_00000_generated_v_test are both failing to build

@SteveBronder
Copy link
Collaborator Author

Yes it looks like there was a conflict with some code using using boost::math::lgamma. We shouldn't have those anyway so I'm going to remove them.

@SteveBronder SteveBronder marked this pull request as ready for review July 15, 2025 21:21
@stan-buildbot
Copy link
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
arma/arma.stan 0.34 0.3 1.12 11.08% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.11 9.52% faster
gp_regr/gen_gp_data.stan 0.03 0.02 1.11 9.85% faster
gp_regr/gp_regr.stan 0.09 0.09 1.06 5.46% faster
sir/sir.stan 70.07 67.06 1.04 4.3% faster
irt_2pl/irt_2pl.stan 4.17 3.92 1.06 5.97% faster
eight_schools/eight_schools.stan 0.06 0.05 1.11 9.98% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.26 0.24 1.07 6.55% faster
pkpd/one_comp_mm_elim_abs.stan 19.13 18.63 1.03 2.59% faster
garch/garch.stan 0.41 0.4 1.02 2.33% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.75 2.6 1.06 5.66% faster
arK/arK.stan 1.83 1.71 1.08 7.05% faster
gp_pois_regr/gp_pois_regr.stan 2.82 2.66 1.06 5.49% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 9.01 8.34 1.08 7.38% faster
performance.compilation 180.04 174.97 1.03 2.82% faster
Mean result: 1.0692808402848126

Jenkins Console Log
Blue Ocean
Commit hash: 42e76f7fa79cf13a1e09768a622d7c65d3dfc138


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: 2400.000
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
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.

Undefined behavior in combination of apply_scalar_binary/make_holder/to_ref_if
3 participants