Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_pose_prior_error_function.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
12#include "momentum/math/mppca.h"
13
14namespace momentum {
15
16namespace {
17
18template <typename T>
19Eigen::VectorX<T> mapParameters(
20 Eigen::Ref<const Eigen::VectorX<T>> in,
21 const std::vector<size_t>& mp) {
22 Eigen::VectorX<T> res = Eigen::VectorX<T>::Zero(mp.size());
23 for (size_t i = 0; i < mp.size(); i++) {
24 if (mp[i] != kInvalidIndex) {
25 res[i] = in[mp[i]];
26 }
27 }
28 return res;
29}
30
31} // namespace
32
33template <typename T>
35 const Skeleton& skel,
36 const ParameterTransform& pt,
37 std::vector<std::string> names)
38 : PosePriorErrorFunctionT<T>(skel, pt, std::make_shared<MppcaT<T>>()),
39 names_(std::move(names)) {}
40
41template <typename T>
43 default;
44
45template <typename T>
47 const VectorX<T>& pi,
48 const MatrixX<T>& mmu,
49 const std::vector<MatrixX<T>>& W,
50 const VectorX<T>& sigma) {
51 MT_THROW_IF(W.empty(), "Empty W matrix in setPosePrior().");
52
53 for (const auto& W_i : W) {
55 W_i.rows() != W[0].rows() || W_i.cols() != W[0].cols(),
56 "Expected matching dimensions for all matrices in W in setPosePrior.");
57 }
58
59 pi_ = std::move(pi);
60 mmu_ = std::move(mmu);
61 W_ = std::move(W);
62 sigma_ = std::move(sigma);
63
64 auto mppca = std::make_shared<MppcaT<T>>();
65 mppca->set(pi_, mmu_, W_, sigma_.array().square());
67 mppca->d != names_.size(),
68 "Mismatch in pose prior; expected number of names to match dimension.");
69 mppca->names = names_;
71}
72
73template <typename T>
75 return {kPi, kMu, kW, kSigma};
76}
77
78template <typename T>
80 const std::string& name) const {
81 if (name == kPi) {
82 return this->pi_.size();
83 } else if (name == kMu) {
84 return this->mmu_.size();
85 } else if (name == kW) {
86 Eigen::Index result = 0;
87 for (const auto& W_i : W_) {
88 result += W_i.size();
89 }
90 return result;
91 } else if (name == kSigma) {
92 return sigma_.size();
93 } else {
95 "Unknown input to FullyDifferentiablePosePriorErrorFunctionT<T>::getInputSize: {}", name);
96 }
97}
98
99template <typename T>
101 const std::string& name,
102 Eigen::Ref<Eigen::VectorX<T>> value) const {
103 MT_THROW_IF(!this->posePrior_, "No pose prior loaded, can't set values.");
104
105 const auto& posePrior = *this->posePrior_;
106
107 const Eigen::Index p = posePrior.p;
108 const Eigen::Index d = posePrior.d;
109
110 if (name == kPi) {
111 MT_CHECK(this->pi_.size() == p);
112 value = this->pi_.template cast<T>();
113 } else if (name == kMu) {
114 // mmu stores the means in the rows of mmu:
115 MT_CHECK(this->mmu_.rows() == p);
116 MT_CHECK(this->mmu_.cols() == d);
117
118 for (Eigen::Index iMix = 0; iMix < p; ++iMix) {
119 value.segment(iMix * d, d) = this->mmu_.row(iMix).template cast<T>();
120 }
121 } else if (name == kW) {
122 MT_CHECK(this->W_.size() == p);
123 Eigen::Index offset = 0;
124 for (Eigen::Index iMix = 0; iMix < p; ++iMix) {
125 const auto& W_i = this->W_[iMix];
126 MT_CHECK(W_i.rows() == d);
127 for (Eigen::Index j = 0; j < W_i.cols(); ++j) {
128 value.segment(offset, d) = W_i.col(j).template cast<T>();
129 offset += d;
130 }
131 }
132 } else if (name == kSigma) {
133 MT_CHECK(this->sigma_.size() == p);
134 value = this->sigma_.template cast<T>();
135 } else {
136 MT_THROW(
137 "Unknown input to FullyDifferentiablePosePriorErrorFunctionT<T>::getInputSize: {}", name);
138 }
139}
140
141template <typename T>
143 const std::string& name,
144 Eigen::Ref<const Eigen::VectorX<T>> value) {
145 MT_THROW_IF(!this->posePrior_, "No pose prior loaded, can't set values.");
146
147 const auto& posePrior = *this->posePrior_;
148
149 const Eigen::Index p = posePrior.p;
150 const Eigen::Index d = posePrior.d;
151
152 if (name == kPi) {
153 MT_CHECK(this->pi_.size() == p);
154 this->pi_ = value;
155 } else if (name == kMu) {
156 // mmu stores the means in the rows of mmu:
157 MT_CHECK(this->mmu_.rows() == p);
158 MT_CHECK(this->mmu_.cols() == d);
159
160 for (Eigen::Index iMix = 0; iMix < p; ++iMix) {
161 this->mmu_.row(iMix) = value.segment(iMix * d, d);
162 }
163 } else if (name == kW) {
164 MT_CHECK(this->W_.size() == p);
165 Eigen::Index offset = 0;
166 for (Eigen::Index iMix = 0; iMix < p; ++iMix) {
167 auto& W_i = this->W_[iMix];
168 MT_CHECK(W_i.rows() == d);
169 for (Eigen::Index j = 0; j < W_i.cols(); ++j) {
170 W_i.col(j) = value.segment(offset, d).transpose();
171 offset += d;
172 }
173 }
174 } else if (name == kSigma) {
175 MT_CHECK(this->sigma_.size() == p);
176 this->sigma_ = value.cwiseMax(0);
177 } else {
178 MT_THROW(
179 "Unknown input to FullyDifferentiablePosePriorErrorFunctionT<T>::getInputSize: {}", name);
180 }
181
182 // Update the Mppca model:
183 auto mppca = std::make_shared<MppcaT<T>>();
184 mppca->set(pi_, mmu_, W_, sigma_.array().square());
185 mppca->names = names_;
187}
188
189template <typename T>
191 const std::string& inputName,
192 const ModelParametersT<T>& params,
193 const SkeletonStateT<T>& /* state */,
194 Eigen::Ref<const Eigen::VectorX<T>> inputVec) {
195 MT_THROW_IF(!this->posePrior_, "No pose prior loaded, can't set values.");
196
197 const auto& posePrior = *this->posePrior_;
198
199 const Eigen::Index d = posePrior.d;
200
201 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(getInputSize(inputName));
202 size_t modeIdx = 0;
203 Eigen::VectorX<T> bestDiff;
204 T minDist, bestR;
205 PosePriorErrorFunctionT<T>::getBestFitMode(params, modeIdx, bestDiff, bestR, minDist);
206
207 if (modeIdx == kInvalidIndex) {
208 return result;
209 }
210
211 const Eigen::VectorX<T> subParams = mapParameters<T>(params.v, this->ppMap_);
212 const Eigen::VectorX<T> subInput = mapParameters<T>(inputVec, this->ppMap_);
213
214 if (inputName == kMu) {
215 // Gradient is just weight * C^{-1} * (theta - mu) so the derivative is pretty simple:
216 const auto weight = this->kPosePriorWeight * this->weight_;
217 result.segment(modeIdx * d, d) = -weight * posePrior.Cinv[modeIdx] * subInput;
218 } else if (inputName == kSigma) {
219 // We need to know the derivative of the C^{-1} matrix wrt sigma.
220 // Computing this requires knowing the derivative of the matrix inverse.
221 // We have the following identity: http://matrixcookbook.com
222 // d(Ainv)/dsigma = -(Ainv) dA/dSigma (Ainv)
223 // We know that A = sigma^2 * I + ..., so
224 // dA/dSigma = 2 * sigma * I
225 // We also have that the derivative of A_ii wrt sigma is just
226 // Therefore
227 // d(Ainv)/dsigma = -(Ainv) * (2*sigma*I) * Ainv
228 // = -2 * sigma * Ainv * Ainv
229 //
230 // Now remember that the final thing we want to compute is actually v^T * dGrad/dSigma.
231 // and the gradient is:
232 // grad = weight * Ainv * (theta - mu)
233 // Our standard chain rule expansion of dLoss/dSigma is:
234 // v^T dGrad/dSigma
235 // = v^T (weight * dAinv/dSigma * (theta - mu))
236 // = v^T (weight * -2 * sigma * Ainv * Ainv * (theta - mu))
237 // = -2 * weight * sigma * v^T * [ Ainv * Ainv * (theta - mu) ]
238 // and we can reorder the last quantity so we do matrix-vector instead of
239 // matrix-matrix multiplication.
240 const auto weight = this->kPosePriorWeight * this->weight_;
241 const T sigma = sigma_[modeIdx];
242 const Eigen::VectorX<T> diff = subParams - posePrior.mu.row(modeIdx).transpose();
243 result(modeIdx) = (-T(2) * sigma * weight) *
244 (posePrior.Cinv[modeIdx] * subInput).dot(posePrior.Cinv[modeIdx] * diff);
245 } else if (inputName == kW) {
246 if (W_.empty()) {
247 return result;
248 }
249
250 const auto weight = this->kPosePriorWeight * this->weight_;
251
252 // We need to know the derivative of the C^{-1} matrix wrt W.
253 // Computing this requires knowing the derivative of the matrix inverse.
254 // We have the following identity: http://matrixcookbook.com
255 // d(Ainv)/dW_jk = -(Ainv) dA/dW_jk (Ainv)
256 // Recall that
257 // A = sigma^2*I + W * W^T
258 // dA/dW_jk = W * dW/dW_ik^T + dW/dW_ik * W^T
259 // where these dW/dW_ik matrices have a single 1 in a matrix of zeros
260 // that plucks out the kth column from W:
261 // [ ] [ | ]
262 // dA/dW_jk = [ --- W_:k^T --- ] + [ W_:k ]
263 // [ ] [ | ]
264 //
265 // Recall that the full quantity we want is v^T * dGrad/dW_jk
266 // Since grad = weight * Ainv * (theta - mu), we can compute
267 // v^T * dGrad/dW_jk
268 // = v^T * weight * dAinv/dW_jk * (theta - mu)
269 // = weight * v^T * -(Ainv) dA/dW_jk (Ainv) * (theta - mu)
270 // If we rearrange the parentheses and use the fact that A is symmetric, this becomes
271 // = -weight * (Ainv * v)^T dA/dW_jk (Ainv * (theta - mu))
272 // ---------- -------------------
273 // The quantities on the ends can be computed once and reused, and only the dA/dW_jk
274 // changes. But this matrix has the simple sparsity pattern reported above, so multiplying
275 // by it produces a vector where one entry is a dot product with the appropriate column of
276 // W and the other elements are zero.
277 const Eigen::MatrixX<T>& W_i = W_[modeIdx];
278 MT_CHECK(W_i.rows() == d);
279 const Eigen::Index W_cols = W_i.cols();
280
281 const Eigen::Index result_offset = W_cols * d * modeIdx;
282
283 const Eigen::MatrixX<T>& Cinv = posePrior.Cinv[modeIdx];
284
285 const Eigen::VectorX<T> dLoss_times_Cinv = Cinv * subInput;
286 const Eigen::VectorX<T> diff = subParams - posePrior.mu.row(modeIdx).transpose();
287 const Eigen::VectorX<T> Cinv_times_diff = Cinv * diff;
288
289 for (Eigen::Index j = 0; j < d; ++j) {
290 for (Eigen::Index k = 0; k < W_cols; ++k) {
291 const T dGrad_dInput_dot_v = -weight *
292 (dLoss_times_Cinv.dot(W_i.col(k)) * Cinv_times_diff[j] +
293 W_i.col(k).dot(Cinv_times_diff) * dLoss_times_Cinv[j]);
294 result(result_offset + k * d + j) = dGrad_dInput_dot_v;
295 }
296 }
297 } else if (inputName == kPi) {
298 // The derivatives of the mixture weights are, for all practical purposes, zero;
299 // since they are constant wrt any particular mixture they only turn up in the
300 // relative weighting of the gradients and since the constant terms in the
301 // probability terms that are used for that weighting almost always get swamped
302 // by the exponential falloff as we move away from the mean we can safely ignore
303 // them.
304 }
305
306 return result;
307}
308
311
312} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
void setPosePrior(const VectorX< T > &pi, const MatrixX< T > &mmu, const std::vector< MatrixX< T > > &W, const VectorX< T > &sigma)
void getInputImp(const std::string &name, Eigen::Ref< Eigen::VectorX< T > > value) const final
void setInputImp(const std::string &name, Eigen::Ref< const Eigen::VectorX< T > > value) final
Eigen::VectorX< T > d_gradient_d_input_dot(const std::string &inputName, const ModelParametersT< T > &params, const SkeletonStateT< T > &state, Eigen::Ref< const Eigen::VectorX< T > > inputVec) final
FullyDifferentiablePosePriorErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, std::vector< std::string > names)
void setPosePrior(std::shared_ptr< const MppcaT< T > > pp)
std::shared_ptr< const MppcaT< T > > posePrior_
void getBestFitMode(const ModelParametersT< T > &params, size_t &bestIdx, Eigen::VectorX< T > &bestDiff, T &bestR, T &minDist) const
PosePriorErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, std::shared_ptr< const MppcaT< T > > pp)
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
SkeletonT< float > Skeleton
Definition fwd.h:263
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Eigen::VectorX< T > mapParameters(const ModelParametersT< T > &in, const std::vector< size_t > &mp)
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Mixture of Probabilistic Principal Component Analyzers (MPPCA).
Definition mppca.h:29
Represents the complete state of a skeleton.