Automatic Differentiation
 
Loading...
Searching...
No Matches
log_softmax.hpp
Go to the documentation of this file.
1#ifndef STAN_MATH_FWD_FUN_LOG_SOFTMAX_HPP
2#define STAN_MATH_FWD_FUN_LOG_SOFTMAX_HPP
3
12
13namespace stan {
14namespace math {
15
23template <typename T, require_std_vector_st<is_fvar, T>* = nullptr>
24inline auto log_softmax(T&& x) {
25 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
26 return log_softmax(std::forward<decltype(v)>(v));
27 });
28}
29
38template <typename Vec, require_eigen_vector_vt<is_fvar, Vec>* = nullptr>
39inline auto log_softmax(Vec&& x) {
40 using vec = std::decay_t<Vec>;
41 constexpr int Rows = vec::RowsAtCompileTime;
42 constexpr int Cols = vec::ColsAtCompileTime;
43 using T = typename value_type_t<Vec>::Scalar;
44 check_nonzero_size("log_softmax", "x", x);
45 decltype(auto) x_ref = to_ref(std::forward<Vec>(x));
46 const auto s = softmax(value_of(x_ref));
47 const auto d_in = x_ref.d();
48 const auto dot_sd = s.dot(d_in);
49 Eigen::Matrix<fvar<T>, Rows, Cols> result(x_ref.size());
50 result.val() = s.array().log().matrix();
51 result.d() = (d_in.array() - dot_sd).matrix();
52 return result;
53}
54
55} // namespace math
56} // namespace stan
57#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
auto log_softmax(T &&x)
Return the log softmax of each vector in a container of fvar values.
void check_nonzero_size(const char *function, const char *name, const T_y &y)
Check if the specified matrix/vector is of non-zero size.
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 ...