Automatic Differentiation
 
Loading...
Searching...
No Matches
softmax.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_REV_FUN_SOFTMAX_HPP
2#define STAN_MATH_REV_FUN_SOFTMAX_HPP
3
13
14namespace stan {
15namespace math {
16
24template <typename T, require_rev_matrix_t<T>* = nullptr>
25inline auto softmax(T&& x) {
26 auto x_arena = to_arena(std::forward<T>(x));
27 if (x_arena.size() == 0) {
28 return x_arena;
29 }
30 using return_t
31 = return_var_matrix_t<plain_type_t<decltype(x_arena.val())>, T>;
32 arena_t<return_t> res = softmax(x_arena.val());
33 reverse_pass_callback([x_arena, res]() mutable {
34 x_arena.adj().array()
35 += res.val().array() * (res.adj().array() - res.val().dot(res.adj()));
36 });
37 return res;
38}
39
47template <typename T, require_std_vector_st<is_var, T>* = nullptr>
48inline auto softmax(T&& x) {
49 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
50 return softmax(std::forward<decltype(v)>(v));
51 });
52}
53
54} // namespace math
55} // namespace stan
56#endif
void reverse_pass_callback(F &&functor)
Puts a callback on the autodiff stack to be called in reverse pass.
auto softmax(T &&x)
Return the softmax of each vector in a container of fvar values.
Definition softmax.hpp:23
arena_t< T > to_arena(const T &a)
Converts given argument into a type that either has any dynamic allocation on AD stack or schedules i...
Definition to_arena.hpp:25
typename plain_type< std::decay_t< T > >::type plain_type_t
std::conditional_t< is_any_var_matrix< ReturnType, Types... >::value, stan::math::var_value< stan::math::promote_scalar_t< double, plain_type_t< ReturnType > > >, stan::math::promote_scalar_t< stan::math::var_value< double >, plain_type_t< ReturnType > > > return_var_matrix_t
Given an Eigen type and several inputs, determine if a matrix should be var<Matrix> or Matrix<var>.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...