Skip to content

Commit 49b92b2

Browse files
authored
Merge pull request #3050 from stan-dev/5.0-breaking-changes
5.0 breaking changes
2 parents 3fcfe24 + 243d90c commit 49b92b2

423 files changed

Lines changed: 2012 additions & 5966 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

doxygen/contributor_help_pages/common_pitfalls.md

Lines changed: 138 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,6 @@ The implementation of @ref stan::math::make_holder is [here](https://github.com/
154154

155155
### Move Semantics
156156

157-
In general, Stan Math does not use move semantics very often.
158-
This is because of our arena allocator.
159157
Move semantics generally work as
160158

161159
```cpp
@@ -179,6 +177,96 @@ We can see in the above that the standard style of a move (the constructor takin
179177
But in Stan, particularly for reverse mode, we need to keep memory around even if it's only temporary for when we call the gradient calculations in the reverse pass.
180178
And since memory for reverse mode is stored in our arena allocator no copying happens in the first place.
181179
180+
Functions for Stan Math's reverse mode autodiff should use [_perfect forwarding_](https://drewcampbell92.medium.com/understanding-move-semantics-and-perfect-forwarding-part-3-65575d523ff8) arguments. Perfect forwarding arguments use a template parameter wit no attributes such as `const` and `volatile` and have a double ampersand `&&` next to them.
181+
182+
```c++
183+
template <typename T>
184+
auto my_function(T&& x) {
185+
return my_other_function(std::forward<T>(x));
186+
}
187+
```
188+
189+
The `std::forward<T>` in the in the code above tells the compiler that if `T` is deduced to be an rvalue reference (such as `Eigen::MatrixXd&&`), then it should be moved to `my_other_function`, where there it can possibly use another objects move constructor to reuse memory.
190+
A perfect forwarding argument of a function accepts any reference type as its input argument.
191+
The above signature is equivalent to writing out several functions with different reference types
192+
193+
```c++
194+
// Accepts a plain lvalue reference
195+
auto my_function(Eigen::MatrixXd& x) {
196+
return my_other_function(x);
197+
}
198+
// Accepts a const lvalue reference
199+
auto my_function(const Eigen::MatrixXd& x) {
200+
return my_other_function(x);
201+
}
202+
// Accepts an rvalue reference
203+
auto my_function(Eigen::MatrixXd&& x) {
204+
return my_other_function(std::move(x));
205+
}
206+
// Accepts a const rvalue reference
207+
auto my_function(const Eigen::MatrixXd&& x) {
208+
return my_other_function(std::move(x));
209+
}
210+
```
211+
212+
In Stan, perfect forwarding is used in reverse mode functions which can accept an Eigen matrix type.
213+
214+
```c++
215+
template <typename T, require_eigen_vt<is_var, T>* = nullptr>
216+
inline auto sin(T&& x) {
217+
// Store `x` on the arena
218+
arena_t<T> x_arena(std::forward<T>(x));
219+
arena_t<T> ret(x_arena.val().array().sin().matrix());
220+
reverse_pass_callback([x_arena, ret] mutable {
221+
x_arena.adj() += ret.adj().cwiseProduct(x_arena.val().array().cos().matrix());
222+
});
223+
return ret;
224+
}
225+
```
226+
227+
Let's go through the above line by line.
228+
229+
```c++
230+
template <typename T, require_eigen_vt<is_var, T>* = nullptr>
231+
inline auto sin(T&& x) {
232+
```
233+
234+
The signature for this function has a template `T` that is required to be an Eigen type with a `value_type` that is a `var` type.
235+
The template parameter `T` is then used in the signature as an perfect forwarding argument.
236+
237+
```c++
238+
// Store `x` on the arena
239+
arena_t<T> x_arena(std::forward<T>(x));
240+
```
241+
242+
The input is stored in the arena, which is where the perfect forwarding magic actually occurs.
243+
If `T` is an lvalue type such as `Eigen::MatrixXd&` then `arena_matrix` will use it's copy constructor, creating new memory in Stan's arena allocator and then copying the values of `x` into that memory.
244+
But if `T` was a temporary rvalue type such as `Eigen::MatrixXd&&`, then the `arena_matrix` class will use it's move constructor to place the temporary matrix in Stan's `var_alloc_stack_`.
245+
The `var_alloc_stick_` is used to hold objects that were created outside of the arena allocator but need to be deleted when the arena allocator is cleared.
246+
This allows the `arena_matrix` to reuse the memory from the temporary matrix. Then the matrix will be deleted once arena allocator requests memory to be cleared.
247+
248+
```c++
249+
arena_t<T> ret(x_arena.val().array().sin().matrix());
250+
```
251+
252+
This construction of an `arena_matrix` will *not* use the move constructor for `arena_matrix`.
253+
Here, `x_arena` is an `arena_matrix<T>`, which is then wrapped in an expression to compute the elementwise `sin`.
254+
That expression will be evaluated into new memory allocated in the arena allocator and then a pointer to it will be stored in the `arena_matrix.`
255+
256+
```c++
257+
reverse_pass_callback([x_arena, ret] mutable {
258+
x_arena.adj() += ret.adj().cwiseProduct(x_arena.val().array().cos().matrix());
259+
});
260+
return ret;
261+
```
262+
263+
The rest of this code follows the standard format for the rest of Stan Math's reverse mode that accepts Eigen types as input.
264+
The `reverse_pass_callback` function accepts a lambda as input and places the lambda in Stan's callback stack to be called later when `grad()` is called by the user.
265+
Since `arena_matrix` types only store a pointer to memory allocated elsewhere they are copied into the lambda.
266+
The body of the lambda holds the gradient calculation needed for the reverse mode pass.
267+
268+
Then finally `ret`, the `arena_matrix` type is returned by the function.
269+
182270
When working with arithmetic types, keep in mind that moving Scalars is often less optimal than simply taking their copy.
183271
For instance, Stan's `var` type uses the pointer to implementation (PIMPL) pattern, so it simply holds a pointer of size 8 bytes.
184272
A `double` is also 8 bytes which just so happens to fit exactly in a [word](https://en.wikipedia.org/wiki/Word_(computer_architecture)) of most modern CPUs with at least 64-byte cache lines.
@@ -190,6 +278,45 @@ The general rules to follow for passing values to a function are:
190278
2. If you are writing a function for reverse mode, pass values by `const&`
191279
3. In prim, if you are confident and working with larger types, use perfect forwarding to pass values that can be moved from. Otherwise simply pass values by `const&`.
192280

281+
### Using auto is Dangerous With Eigen Matrix Functions in Reverse Mode
282+
283+
The use of auto with the Stan Math library should be used with care, like in [Eigen](https://eigen.tuxfamily.org/dox/TopicPitfalls.html).
284+
Along with the cautions mentioned in the Eigen docs, there are also memory considerations when using reverse mode automatic differentiation.
285+
When returning from a function in the Stan Math library with an Eigen matrix output with a scalar `var` type, the actual returned type will often be an `arena_matrix<Eigen::Matrix<...>>`.
286+
The `arena_matrix` class is an Eigen matrix where the underlying array of memory is located in Stan's memory arena.
287+
The `arena_matrix` that is returned by Math functions is normally the same one resting in the callback used to calculate gradients in the reverse pass.
288+
Directly changing the elements of this matrix would also change the memory the reverse pass callback sees which would result in incorrect calculations.
289+
290+
The simple solution to this is that when you use a math library function that returns a matrix and then want to assign to any of the individual elements of the matrix, assign to an actual Eigen matrix type instead of using auto.
291+
In the below example, we see the first case which uses auto and will change the memory of the `arena_matrix` returned in the callback for multiply's reverse mode.
292+
Directly below it is the safe version, which just directly assigns to an Eigen matrix type and is safe to do element insertion into.
293+
294+
```c++
295+
Eigen::Matrix<var, -1, 1> y;
296+
Eigen::Matrix<var, -1, -1> X;
297+
// Bad!! Will change memory used by reverse pass callback within multiply!
298+
auto mu = multiply(X, y);
299+
mu(4) = 1.0;
300+
// Good! Will not change memory used by reverse pass callback within multiply
301+
Eigen::Matrix<var, -1, 1> mu_good = multiply(X, y);
302+
mu_good(4) = 1.0;
303+
```
304+
305+
The reason we do this is for cases where function returns are passed to other functions.
306+
An `arena_matrix` will always make a shallow copy when being constructed from another `arena_matrix`, which lets the functions avoid unnecessary copies.
307+
308+
```c++
309+
Eigen::Matrix<var, -1, 1> y1;
310+
Eigen::Matrix<var, -1, -1> X1;
311+
Eigen::Matrix<var, -1, 1> y2;
312+
Eigen::Matrix<var, -1, -1> X2;
313+
auto mu1 = multiply(X1, y1);
314+
auto mu2 = multiply(X2, y2);
315+
// Inputs not copied in this case!
316+
auto z = add(mu1, mu2);
317+
```
318+
319+
193320
### Passing variables that need destructors called after the reverse pass (`make_chainable_ptr`)
194321

195322
When possible, non-arena variables should be copied to the arena to be used in the reverse pass.
@@ -242,22 +369,17 @@ grad();
242369
```
243370

244371
Now `res` is `innocent_return` and we've changed one of the elements of `innocent_return`, but that is also going to change the element of `res` which is being used in our reverse pass callback!
245-
The answer for this is simple but sadly requires a copy.
246372

247-
```cpp
248-
template <typename EigVec, require_eigen_vt<is_var, EigVec>* = nullptr>
249-
inline var cool_fun(const EigVec& v) {
250-
arena_t<EigVec> arena_v(v);
251-
arena_t<EigVec> res = arena_v.val().array() * arena_v.val().array();
252-
reverse_pass_callback([res, arena_v]() mutable {
253-
arena_v.adj().array() += (2.0 * res.adj().array()) * arena_v.val().array();
254-
});
255-
return plain_type_t<EigVec>(res);
256-
}
257-
```
373+
Care must be taken by end users of Stan Math by using `auto` with caution.
374+
When a user wishes to manipulate the coefficients of a matrix that is a return from a function in Stan Math, they should assign the matrix to a plain Eigen type.
258375

259-
we make a deep copy of the return whose inner `vari` will not be the same, but the `var` will produce a new copy of the pointer to the `vari`.
260-
Now the user code above will be protected, and it is safe for them to assign to individual elements of the `auto` returned matrix.
376+
```c++
377+
Eigen::Matrix<var, -1, 1> x = Eigen::Matrix<double, -1, 1>::Random(5);
378+
Eigen::MatrixXd actually_innocent_return = cool_fun(x);
379+
actually_innocent_return.coeffRef(3) = var(3.0);
380+
auto still_unsafe_return = cool_fun2(actually_innocent_return);
381+
grad();
382+
```
261383

262384
### Const correctness, reverse mode autodiff, and arena types
263385

doxygen/contributor_help_pages/distribution_tests.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Here, I'm just going to describe the steps that are taken to run the tests. Deta
2828

2929
1. `make generate-tests` is called.
3030
1. This first builds the `test/prob/generate_tests` executable from `test/prob/generate_tests.cpp`.
31-
2. For each test file inside `test/prob/*/*`, it will call the executable with the test file as the first argument and the number of template instantiations per file within the second argument. For example, for testing the `bernoulli_log()` function, make will call: `test/prob/generate_tests test/prob/bernoulli/bernoulli_test.hpp 100`
31+
2. For each test file inside `test/prob/*/*`, it will call the executable with the test file as the first argument and the number of template instantiations per file within the second argument. For example, for testing the `bernoulli_lpmf()` function, make will call: `test/prob/generate_tests test/prob/bernoulli/bernoulli_test.hpp 100`
3232
The call to the executable will generate 5 different test files, all within the `test/prob/bernoulli/` folder:
3333
- bernoulli\_00000\_generated\_fd\_test.cpp
3434
- bernoulli\_00000\_generated\_ffd\_test.cpp

runTests.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,34 @@
2323

2424
allowed_paths_with_jumbo = [
2525
"test/unit/math/prim/",
26+
"test/unit/math/prim/constraint",
2627
"test/unit/math/",
2728
"test/unit/math/rev/",
29+
"test/unit/math/rev/constraint",
2830
"test/unit/math/fwd/",
31+
"test/unit/math/fwd/constraint",
2932
"test/unit/math/mix/",
3033
"test/unit/math/mix/fun/",
3134
"test/unit/math/opencl/",
3235
"test/unit/",
3336
]
3437

3538
jumbo_folders = [
39+
"test/unit/math/prim/constraint",
3640
"test/unit/math/prim/core",
3741
"test/unit/math/prim/err",
3842
"test/unit/math/prim/fun",
3943
"test/unit/math/prim/functor",
4044
"test/unit/math/prim/meta",
4145
"test/unit/math/prim/prob",
46+
"test/unit/math/rev/constraint",
4247
"test/unit/math/rev/core",
4348
"test/unit/math/rev/err",
4449
"test/unit/math/rev/fun",
4550
"test/unit/math/rev/functor",
4651
"test/unit/math/rev/meta",
4752
"test/unit/math/rev/prob",
53+
"test/unit/math/fwd/constraint",
4854
"test/unit/math/fwd/core",
4955
"test/unit/math/fwd/fun",
5056
"test/unit/math/fwd/functor",
@@ -58,7 +64,9 @@
5864
"test/unit/math/opencl/device_functions",
5965
"test/unit/math/opencl/kernel_generator",
6066
"test/unit/math/opencl/prim",
67+
"test/unit/math/opencl/prim/constraint",
6168
"test/unit/math/opencl/rev",
69+
"test/unit/math/opencl/rev/constraint",
6270
]
6371

6472

stan/math/fwd.hpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55

66
#ifdef STAN_OPENCL
77
#include <stan/math/opencl/prim.hpp>
8+
#include <stan/math/opencl/prim_constraint.hpp>
89
#endif
910

11+
#include <stan/math/fwd/constraint.hpp>
1012
#include <stan/math/fwd/core.hpp>
1113
#include <stan/math/fwd/meta.hpp>
1214
#include <stan/math/fwd/fun.hpp>

stan/math/fwd/constraint.hpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#ifndef STAN_MATH_FWD_CONSTRAINT_HPP
2+
#define STAN_MATH_FWD_CONSTRAINT_HPP
3+
4+
#include <stan/math/prim/fun/Eigen.hpp>
5+
#include <stan/math/fwd/fun/Eigen_NumTraits.hpp>
6+
7+
#include <stan/math/fwd/constraint/unit_vector_constrain.hpp>
8+
9+
#endif

stan/math/fwd/fun/unit_vector_constrain.hpp renamed to stan/math/fwd/constraint/unit_vector_constrain.hpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
#ifndef STAN_MATH_FWD_FUN_UNIT_VECTOR_CONSTRAIN_HPP
2-
#define STAN_MATH_FWD_FUN_UNIT_VECTOR_CONSTRAIN_HPP
1+
#ifndef STAN_MATH_FWD_CONSTRAINT_UNIT_VECTOR_CONSTRAIN_HPP
2+
#define STAN_MATH_FWD_CONSTRAINT_UNIT_VECTOR_CONSTRAIN_HPP
33

44
#include <stan/math/fwd/core.hpp>
55
#include <stan/math/fwd/fun/tcrossprod.hpp>
@@ -8,7 +8,7 @@
88
#include <stan/math/prim/fun/dot_self.hpp>
99
#include <stan/math/prim/fun/Eigen.hpp>
1010
#include <stan/math/prim/fun/inv.hpp>
11-
#include <stan/math/prim/fun/unit_vector_constrain.hpp>
11+
#include <stan/math/prim/constraint/unit_vector_constrain.hpp>
1212
#include <stan/math/prim/fun/tcrossprod.hpp>
1313
#include <cmath>
1414

stan/math/fwd/fun.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@
121121
#include <stan/math/fwd/fun/trigamma.hpp>
122122
#include <stan/math/fwd/fun/trunc.hpp>
123123
#include <stan/math/fwd/fun/typedefs.hpp>
124-
#include <stan/math/fwd/fun/unit_vector_constrain.hpp>
124+
#include <stan/math/fwd/constraint/unit_vector_constrain.hpp>
125125
#include <stan/math/fwd/fun/value_of.hpp>
126126
#include <stan/math/fwd/fun/value_of_rec.hpp>
127127

stan/math/mix.hpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <stan/math/mix/fun.hpp>
66
#include <stan/math/mix/functor.hpp>
77

8+
#include <stan/math/fwd/constraint.hpp>
89
#include <stan/math/fwd/core.hpp>
910
#include <stan/math/fwd/meta.hpp>
1011
#include <stan/math/fwd/fun.hpp>
@@ -13,8 +14,10 @@
1314

1415
#ifdef STAN_OPENCL
1516
#include <stan/math/opencl/rev.hpp>
17+
#include <stan/math/opencl/rev_constraint.hpp>
1618
#endif
1719

20+
#include <stan/math/rev/constraint.hpp>
1821
#include <stan/math/rev/core.hpp>
1922
#include <stan/math/rev/meta.hpp>
2023
#include <stan/math/rev/fun.hpp>

stan/math/opencl/prim.hpp

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@
9999
#include <stan/math/opencl/zeros_strict_tri.hpp>
100100
#include <stan/math/opencl/qr_decomposition.hpp>
101101

102+
#include <stan/math/opencl/prim_constraint.hpp>
103+
102104
#include <stan/math/opencl/prim/add_diag.hpp>
103105
#include <stan/math/opencl/prim/append_array.hpp>
104106
#include <stan/math/opencl/prim/bernoulli_cdf.hpp>
@@ -172,7 +174,6 @@
172174
#include <stan/math/opencl/prim/inv_cloglog.hpp>
173175
#include <stan/math/opencl/prim/inv_gamma_lpdf.hpp>
174176
#include <stan/math/opencl/prim/inv_sqrt.hpp>
175-
#include <stan/math/opencl/prim/lb_constrain.hpp>
176177
#include <stan/math/opencl/prim/log_mix.hpp>
177178
#include <stan/math/opencl/prim/log_softmax.hpp>
178179
#include <stan/math/opencl/prim/logistic_cdf.hpp>
@@ -184,7 +185,6 @@
184185
#include <stan/math/opencl/prim/lognormal_lccdf.hpp>
185186
#include <stan/math/opencl/prim/lognormal_lcdf.hpp>
186187
#include <stan/math/opencl/prim/lognormal_lpdf.hpp>
187-
#include <stan/math/opencl/prim/lub_constrain.hpp>
188188
#include <stan/math/opencl/prim/matrix_power.hpp>
189189
#include <stan/math/opencl/prim/mdivide_left_tri_low.hpp>
190190
#include <stan/math/opencl/prim/mdivide_right_tri_low.hpp>
@@ -201,7 +201,6 @@
201201
#include <stan/math/opencl/prim/normal_lcdf.hpp>
202202
#include <stan/math/opencl/prim/normal_lpdf.hpp>
203203
#include <stan/math/opencl/prim/num_elements.hpp>
204-
#include <stan/math/opencl/prim/offset_multiplier_constrain.hpp>
205204
#include <stan/math/opencl/prim/ordered_logistic_glm_lpmf.hpp>
206205
#include <stan/math/opencl/prim/ordered_logistic_lpmf.hpp>
207206
#include <stan/math/opencl/prim/pareto_cdf.hpp>
@@ -266,12 +265,10 @@
266265
#include <stan/math/opencl/prim/to_row_vector.hpp>
267266
#include <stan/math/opencl/prim/to_vector.hpp>
268267
#include <stan/math/opencl/prim/trace.hpp>
269-
#include <stan/math/opencl/prim/ub_constrain.hpp>
270268
#include <stan/math/opencl/prim/uniform_cdf.hpp>
271269
#include <stan/math/opencl/prim/uniform_lccdf.hpp>
272270
#include <stan/math/opencl/prim/uniform_lcdf.hpp>
273271
#include <stan/math/opencl/prim/uniform_lpdf.hpp>
274-
#include <stan/math/opencl/prim/unit_vector_constrain.hpp>
275272
#include <stan/math/opencl/prim/variance.hpp>
276273
#include <stan/math/opencl/prim/weibull_cdf.hpp>
277274
#include <stan/math/opencl/prim/weibull_lccdf.hpp>

stan/math/opencl/prim/lb_constrain.hpp renamed to stan/math/opencl/prim/constraint/lb_constrain.hpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
#ifndef STAN_MATH_OPENCL_PRIM_LB_CONSTRAIN_HPP
2-
#define STAN_MATH_OPENCL_PRIM_LB_CONSTRAIN_HPP
1+
#ifndef STAN_MATH_OPENCL_PRIM_CONSTRAINT_LB_CONSTRAIN_HPP
2+
#define STAN_MATH_OPENCL_PRIM_CONSTRAINT_LB_CONSTRAIN_HPP
33
#ifdef STAN_OPENCL
44

55
#include <stan/math/opencl/prim/sum.hpp>

0 commit comments

Comments
 (0)