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
12
13namespace stan {
14namespace math {
15
23template <typename T, require_rev_matrix_t<T>* = nullptr>
24inline auto softmax(T&& x) {
25 auto x_arena = to_arena(std::forward<T>(x));
26 using return_t
27 = return_var_matrix_t<plain_type_t<decltype(x_arena.val())>, T>;
28 if (x_arena.size() == 0) {
29 return x_arena;
30 }
31 arena_t<return_t> res = softmax(x_arena.val());
32 reverse_pass_callback([x_arena, res]() mutable {
33 x_arena.adj().array()
34 += res.val().array() * (res.adj().array() - res.val().dot(res.adj()));
35 });
36 return res;
37}
38
46template <typename T, require_std_vector_st<is_var, T>* = nullptr>
47inline auto softmax(T&& x) {
48 return apply_vector_unary<T>::apply(std::forward<T>(x), [](auto&& v) {
49 return softmax(std::forward<decltype(v)>(v));
50 });
51}
52
53} // namespace math
54} // namespace stan
55#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:22
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 ...