-
Notifications
You must be signed in to change notification settings - Fork 5
/
momentum_handler.hpp
104 lines (88 loc) · 2.43 KB
/
momentum_handler.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once
#include <random>
#include <autoppl/mcmc/hmc/var_adapter.hpp>
namespace ppl {
namespace mcmc {
/**
* Adapts momentum variance and handles everything related to momentum.
*/
template <class AdapterPolicy>
struct MomentumHandler;
/**
* Unit variance with no adaptation.
*/
template <>
struct MomentumHandler<unit_var>
{
using adapter_policy_t = unit_var;
// Constructor takes in size_t for consistent API with other specializations.
MomentumHandler(size_t=0)
: dist(0., 1.)
{}
/*
* Sample from N(0, I)
*/
template <class MatType
, class GenType>
void sample(Eigen::MatrixBase<MatType>& rho,
GenType& gen)
{
rho = MatType::NullaryExpr(rho.rows(),
[&]() { return dist(gen); });
}
/**
* Compute corresponding kinetic energy
*/
template <class MatType>
double kinetic(const Eigen::MatrixBase<MatType>& rho) const
{ return 0.5 * rho.squaredNorm(); }
template <class MatType>
const MatType& dkinetic_dr(const MatType& rho) const
{ return rho; }
private:
std::normal_distribution<> dist;
};
/**
* Diagonal variance with adaptation.
*/
template <>
struct MomentumHandler<diag_var>
{
using adapter_policy_t = diag_var;
using variance_t = Eigen::VectorXd;
// initialize m inverse to be identity
MomentumHandler(size_t n_params)
: dist(0., 1.)
, m_inverse_(n_params)
{
m_inverse_.setOnes();
}
/**
* Sample from N(0, M) where M inverse ~ sample variance matrix
*/
template <class MatType
, class GenType>
void sample(Eigen::MatrixBase<MatType>& rho,
GenType& gen)
{
rho = MatType::NullaryExpr(rho.rows(),
[&]() { return dist(gen); });
rho.array() /= m_inverse_.array().sqrt();
}
/**
* Compute corresponding kinetic energy
*/
template <class MatType>
double kinetic(const Eigen::MatrixBase<MatType>& rho) const
{ return 0.5 * rho.dot(dkinetic_dr(rho)); }
template <class MatType>
auto dkinetic_dr(const Eigen::MatrixBase<MatType>& rho) const
{ return (m_inverse_.array() * rho.array()).matrix(); }
variance_t& get_m_inverse() { return m_inverse_; }
const variance_t& get_m_inverse() const { return m_inverse_; }
private:
std::normal_distribution<> dist;
variance_t m_inverse_;
};
} // namespace mcmc
} // namespace ppl