Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fully_differentiable_body_ik.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/common/log.h"
15
16#include <Eigen/Eigenvalues>
17
18namespace momentum {
19
20template <typename T>
21std::vector<Eigen::Index> computeSubsetParameterIndices(
22 const ParameterTransformT<T>& parameterTransform,
23 const ParameterSet& activeParams) {
24 std::vector<Eigen::Index> result;
25 for (size_t i = 0; i < parameterTransform.numAllModelParameters(); ++i) {
26 if (activeParams.test(i)) {
27 result.push_back(i);
28 }
29 }
30
31 return result;
32}
33
34template <typename T>
35Eigen::VectorX<T> extractSubsetVec(
36 Eigen::Ref<const Eigen::VectorX<T>> fullVec,
37 const std::vector<Eigen::Index>& subsetIndexToFullParamIndex) {
38 const Eigen::Index nSubset = subsetIndexToFullParamIndex.size();
39 Eigen::VectorX<T> result(nSubset);
40 for (Eigen::Index iSubset = 0; iSubset < nSubset; ++iSubset) {
41 result(iSubset) = fullVec(subsetIndexToFullParamIndex[iSubset]);
42 }
43 return result;
44}
45
46template <typename T>
47Eigen::MatrixX<T> extractSubsetMat(
48 Eigen::Ref<const Eigen::MatrixX<T>> fullMat,
49 const std::vector<Eigen::Index>& subsetIndexToFullParamIndex) {
50 const Eigen::Index nSubset = subsetIndexToFullParamIndex.size();
51 Eigen::MatrixX<T> result(fullMat.rows(), nSubset);
52 for (Eigen::Index iSubset = 0; iSubset < nSubset; ++iSubset) {
53 result.col(iSubset) = fullMat.col(subsetIndexToFullParamIndex[iSubset]);
54 }
55 return result;
56}
57
58template <typename T>
59Eigen::VectorX<T> subsetVecToFullVec(
60 Eigen::Ref<const Eigen::VectorX<T>> subsetVec,
61 const std::vector<Eigen::Index>& subsetIndexToFullParamIndex,
62 Eigen::Index fullVecSize) {
63 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(fullVecSize);
64 for (size_t iSubset = 0; iSubset < subsetIndexToFullParamIndex.size(); ++iSubset) {
65 result[subsetIndexToFullParamIndex[iSubset]] = subsetVec[iSubset];
66 }
67 return result;
68}
69
70float sqr(float val) {
71 return val * val;
72}
73
74template <typename T>
75Eigen::VectorX<T> hessianInverseTimes(
76 Eigen::Ref<const Eigen::MatrixX<T>> jacobian,
77 Eigen::Ref<const Eigen::VectorX<T>> v) {
78 // Use approximate Hessian:
79 // Hess ~ J^T * J
80 // We will use the SVD on J as follows:
81 // J = U * S * V^T
82 // Hess = 2 * J^T * J = (U * S * V^T)^T * (U * S * V^T)
83 // = 2 * V * S * U^T * U * S * V^T
84 // = 2 * V * S^2 * V^T
85 // This is equivalent to performing an eigenvalue decomposition
86 // on the Hessian, and lets us ensure that the Hessian is actually
87 // invertible.
88 //
89 // Note that the particular SVD used here is not terribly fast for large n;
90 // we should consider switching to the one in LAPACK (the divide-and-conquer
91 // version in Eigen is apparently not reliable with -ffast-math).
92 Eigen::JacobiSVD<Eigen::MatrixX<T>> svd(jacobian, Eigen::ComputeThinV);
93
94 // To get the Hess^{-1} * v, we need:
95 // 2 * V * S^2 * V^T * w = v
96 // w = 0.5 * V^T * v)
97 // V^T * w = 0.5 * (S^2)^{-1} * V^T * v
98 // w = 0.5 * V * (S^2)^{-1} * V^T * v
99 Eigen::VectorX<T> tmp = svd.matrixV().transpose() * v;
100 for (Eigen::Index i = 0; i < tmp.size(); ++i) {
101 const float sSqr = sqr(svd.singularValues()(i));
102 if (sSqr < 1e-5f) {
103 tmp(i) = 0;
104 } else {
105 tmp(i) /= sSqr;
106 }
107 }
108 return 0.5f * svd.matrixV() * tmp;
109}
110
111template <typename T>
112std::vector<ErrorFunctionDerivativesT<T>> d_modelParams_d_inputs(
113 const Skeleton& skeleton,
114 const ParameterTransformT<T>& parameterTransform,
115 const ParameterSet& activeParams,
116 const ModelParametersT<T>& modelParameters,
117 SkeletonSolverFunctionT<T>& solverFunction,
118 Eigen::Ref<const Eigen::VectorX<T>> dLoss_dModelParams,
119 T* gradientRmse) {
120 std::vector<ErrorFunctionDerivativesT<T>> result(solverFunction.getErrorFunctions().size());
121
122 const std::vector<Eigen::Index> subsetIndexToFullParamIndex =
123 computeSubsetParameterIndices(parameterTransform, activeParams);
124 const Eigen::Index nFullParams = parameterTransform.numAllModelParameters();
125
126 Eigen::MatrixX<T> jacobian_full;
127 Eigen::VectorX<T> residual_full;
128
129 // Some basic definitions:
130 // theta_j are the model parameters, basically the skeleton pose.
131 // w_j are the "other" inputs that affect the error function values. Here I
132 // am thinking of things like constraint weights, etc.
133 // E(theta_i, w_j) is the energy function our IK solver is minimizing.
134 //
135 // At the minimum, we have the gradient equal to zero:
136 // grad E(theta, w) = dE/dTheta = 0
137 //
138 // Let f(theta, w) = dE/dTheta.
139 // By the implicit function theorem, under certain assumptions about
140 // continuity etc., there exists a function g(w) such that f(theta = g(w), w)
141 // = 0; that is, the energy function is still minimized. Basically, g(w) maps
142 // from any new (but sufficiently close) value of w to a new value of theta.
143 //
144 // Now, what we want is the _gradient_ of g, this will tell us how theta
145 // changes as w varies. By the IFT again:
146 // dg/dw = (-df/dTheta)^{-1} * df/dw
147 // The first term (df/dTheta) is just the Hessian, but as is typical we will
148 // approximate it using the Gauss-Newton approximation.
149 // df/dw is how the gradient changes as a function of w,
150 // d/dw(dE/dTheta) = d^2E/(dTheta dw)
151 // This is going to be a big, very sparse matrix; typical values are like n ~
152 // 50 for the pose vector and m ~ 200 is the number of constraints, and it's
153 // likely that most constraints only affect a few of the pose components.
154 // So then we'd need to multiply that by the inverse Hessian.
155 //
156 // However, at this point it's worth remembering that we actually want to
157 // compute
158 // dLoss/dTheta * dTheta/dw
159 // for some dLoss_dTheta that was passed into this function (this is due to
160 // reverse-mode auto-differentiation). Thus, we can write
161 // dLoss/dTheta * (-df/dTheta)^{-1} * df/dw
162 // We can group the multiplications,
163 // (dLoss/dTheta * (-df/dTheta)^{-1}) * df/dw
164 // This first part is just (Hess^{-1} * dLoss/dTheta^T)^T. The result is a
165 // n-dimensional vector, and we can then multiply this into the df/dw
166 // directly. Thus no need to store any big sparse matrices.
167 size_t actualRows = 0;
168 solverFunction.getJacobian(modelParameters.v, jacobian_full, residual_full, actualRows);
169
170 const Eigen::MatrixX<T> jacobian_subset =
171 extractSubsetMat<T>(jacobian_full, subsetIndexToFullParamIndex);
172 const Eigen::VectorX<T> gradient_subset = 2.0f * jacobian_subset.transpose() * residual_full;
173 if (gradientRmse != nullptr) {
174 *gradientRmse = std::sqrt(gradient_subset.squaredNorm() / gradient_subset.size());
175 }
176
177 const Eigen::VectorX<T> Jinv_times_dLoss_dModelParams_subset = hessianInverseTimes<T>(
178 jacobian_subset, extractSubsetVec<T>(dLoss_dModelParams, subsetIndexToFullParamIndex));
179
180 const Eigen::VectorX<T> Jinv_times_dLoss_dModelParams_full = subsetVecToFullVec<T>(
181 Jinv_times_dLoss_dModelParams_subset, subsetIndexToFullParamIndex, nFullParams);
182
183 MT_LOGD("Jinv_times_dLoss_dModelParams = {}", Jinv_times_dLoss_dModelParams_full.transpose());
184
185 const JointParametersT<T> jointParameters = parameterTransform.apply(modelParameters);
186 SkeletonStateT<T> skelState(jointParameters, skeleton);
187 MeshStateT<T> meshState;
188 if (solverFunction.needsMeshState()) {
189 meshState.update(modelParameters, skelState, solverFunction.getCharacter());
190 }
191
192 const auto& errorFunctions = solverFunction.getErrorFunctions();
193 for (size_t iErr = 0; iErr < errorFunctions.size(); ++iErr) {
194 const auto& errf = errorFunctions[iErr];
195 Eigen::VectorX<T> dGrad_dWeight =
196 Eigen::VectorX<T>::Zero(parameterTransform.numAllModelParameters());
197 errf->getGradient(modelParameters, skelState, meshState, dGrad_dWeight);
198 if (errf->getWeight() != 0) {
199 dGrad_dWeight /= errf->getWeight();
200 }
201 MT_LOGD("dGrad_dWeight = {}", dGrad_dWeight.transpose());
202
203 /*
204 {
205 const auto w_init = errf->getWeight();
206
207 const float eps = 1e-3f;
208 Eigen::VectorX<T> grad_init =
209 Eigen::VectorX<T>::Zero(parameterTransform.numAllModelParameters());
210 errf->getGradient(modelParameters, skelState, grad_init);
211
212 errf->setWeight(w_init + eps);
213 Eigen::VectorX<T> grad_plus =
214 Eigen::VectorX<T>::Zero(parameterTransform.numAllModelParameters());
215 errf->getGradient(modelParameters, skelState, grad_plus);
216 errf->setWeight(w_init);
217
218 Eigen::VectorX<T> diff = (grad_plus - grad_init) / eps;
219 MT_LOGI("dGrad_dWeight (est) = {}", diff.transpose());
220 }
221 */
222
223 result[iErr].errorFunction = errf;
224 result[iErr].gradWeight = -dGrad_dWeight.dot(Jinv_times_dLoss_dModelParams_full);
225
226 auto differentiableErr =
227 std::dynamic_pointer_cast<FullyDifferentiableSkeletonErrorFunctionT<T>>(errf);
228 if (differentiableErr != nullptr) {
229 for (const auto& inputName : differentiableErr->inputs()) {
230 result[iErr].gradInputs.emplace(
231 inputName,
232 differentiableErr->d_gradient_d_input_dot(
233 inputName, modelParameters, skelState, -Jinv_times_dLoss_dModelParams_full));
234 }
235 }
236 }
237
238 return result;
239}
240
241template std::vector<ErrorFunctionDerivativesT<float>> d_modelParams_d_inputs<float>(
242 const Skeleton& skeleton,
243 const ParameterTransformT<float>& parameterTransform,
244 const ParameterSet& activeParams,
245 const ModelParametersT<float>& modelParameters,
246 SkeletonSolverFunctionT<float>& solverFunction,
247 Eigen::Ref<const Eigen::VectorX<float>> dLoss_dModelParams,
248 float* gradientRmse);
249
250template std::vector<ErrorFunctionDerivativesT<double>> d_modelParams_d_inputs<double>(
251 const Skeleton& skeleton,
252 const ParameterTransformT<double>& parameterTransform,
253 const ParameterSet& activeParams,
254 const ModelParametersT<double>& modelParameters,
255 SkeletonSolverFunctionT<double>& solverFunction,
256 Eigen::Ref<const Eigen::VectorX<double>> dLoss_dModelParams,
257 double* gradientRmse);
258
259} // namespace momentum
const Character & getCharacter() const
Provides access to the full character (replaces getSkeleton and getParameterTransform).
const std::vector< std::shared_ptr< SkeletonErrorFunctionT< T > > > & getErrorFunctions() const
bool needsMeshState() const
Checks if any error functions require mesh state.
double getJacobian(const VectorX< T > &parameters, MatrixX< T > &jacobian, VectorX< T > &residual, size_t &actualRows)
Computes the Jacobian matrix for least squares problems.
libfmt formatter support for Eigen types.
#define MT_LOGD(...)
Definition log.h:178
SkeletonT< float > Skeleton
Definition fwd.h:263
std::vector< ErrorFunctionDerivativesT< T > > d_modelParams_d_inputs(const Skeleton &skeleton, const ParameterTransformT< T > &parameterTransform, const ParameterSet &activeParams, const ModelParametersT< T > &modelParameters, SkeletonSolverFunctionT< T > &solverFunction, Eigen::Ref< const Eigen::VectorX< T > > dLoss_dModelParams, T *gradientRmse)
Eigen::MatrixX< T > extractSubsetMat(Eigen::Ref< const Eigen::MatrixX< T > > fullMat, const std::vector< Eigen::Index > &subsetIndexToFullParamIndex)
template std::vector< ErrorFunctionDerivativesT< float > > d_modelParams_d_inputs< float >(const Skeleton &skeleton, const ParameterTransformT< float > &parameterTransform, const ParameterSet &activeParams, const ModelParametersT< float > &modelParameters, SkeletonSolverFunctionT< float > &solverFunction, Eigen::Ref< const Eigen::VectorX< float > > dLoss_dModelParams, float *gradientRmse)
Eigen::VectorX< T > subsetVecToFullVec(Eigen::Ref< const Eigen::VectorX< T > > subsetVec, const std::vector< Eigen::Index > &subsetIndexToFullParamIndex, Eigen::Index fullVecSize)
template std::vector< ErrorFunctionDerivativesT< double > > d_modelParams_d_inputs< double >(const Skeleton &skeleton, const ParameterTransformT< double > &parameterTransform, const ParameterSet &activeParams, const ModelParametersT< double > &modelParameters, SkeletonSolverFunctionT< double > &solverFunction, Eigen::Ref< const Eigen::VectorX< double > > dLoss_dModelParams, double *gradientRmse)
Eigen::VectorX< T > extractSubsetVec(Eigen::Ref< const Eigen::VectorX< T > > fullVec, const std::vector< Eigen::Index > &subsetIndexToFullParamIndex)
T sqr(const T &x)
Computes the square of a value.
Definition utility.h:47
std::vector< Eigen::Index > computeSubsetParameterIndices(const ParameterTransformT< T > &parameterTransform, const ParameterSet &activeParams)
Eigen::VectorX< T > hessianInverseTimes(Eigen::Ref< const Eigen::MatrixX< T > > jacobian, Eigen::Ref< const Eigen::VectorX< T > > v)
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
A vector describing joint parameters, of size numSkeletonJoints * kParametersPerJoint.
Definition types.h:129
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
void update(const ModelParametersT< T > &parameters, const SkeletonStateT< T > &state, const Character &character)
Updates the mesh state based on model parameters and skeleton state.
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
A parameter transform is an abstraction of the joint parameters that maps a model_parameter vector to...
JointParametersT< T > apply(const ModelParametersT< T > &parameters) const
Map model parameters to joint parameters using a linear transformation.
Eigen::Index numAllModelParameters() const
Dimension of all model parameters, including pose, scaling, marker joints, and blendshape parameters ...
Represents the complete state of a skeleton.