Automatic Differentiation
 
Loading...
Searching...
No Matches
softmax.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_SOFTMAX_HPP
2#define STAN_MATH_FWD_FUN_SOFTMAX_HPP
3
10
11namespace stan {
12namespace math {
13
21template <typename T, require_std_vector_st<is_fvar, T>* = nullptr>
22inline auto softmax(T&& x) {
23 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
24 return softmax(std::forward<decltype(v)>(v));
25 });
26}
27
35template <typename Vec, require_eigen_vector_vt<is_fvar, Vec>* = nullptr>
36inline auto softmax(Vec&& x) {
37 using vec = std::decay_t<Vec>;
38 constexpr int Rows = vec::RowsAtCompileTime;
39 constexpr int Cols = vec::ColsAtCompileTime;
40 using T = typename value_type_t<vec>::Scalar;
41 if (x.size() == 0) {
42 return Eigen::Matrix<fvar<T>, Rows, Cols>();
43 }
44 decltype(auto) x_ref = to_ref(std::forward<Vec>(x));
45 const auto s = softmax(value_of(x_ref));
46 const auto d_in = x_ref.d();
47 const auto dot_sd = s.dot(d_in);
48 Eigen::Matrix<fvar<T>, Rows, Cols> result(x_ref.size());
49 result.val() = s;
50 result.d() = (s.array() * (d_in.array() - dot_sd)).matrix();
51 return result;
52}
53
54} // namespace math
55} // namespace stan
56#endif
typename value_type< T >::type value_type_t
Helper function for accessing underlying type.
T value_of(const fvar< T > &v)
Return the value of the specified variable.
Definition value_of.hpp:18
auto softmax(T &&x)
Return the softmax of each vector in a container of fvar values.
Definition softmax.hpp:22
ref_type_t< T && > to_ref(T &&a)
This evaluates expensive Eigen expressions.
Definition to_ref.hpp:18
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...