Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
trust_region_qr.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 <cfloat>
17
18namespace momentum {
19
20template <typename T>
22 const SolverOptions& options,
24 : SolverT<T>(options, solverFun), qrSolver_(0) {
25 // Set default values from TrustRegionQROptions
26 trustRegionRadius_ = TrustRegionQROptions().trustRegionRadius_;
27
28 // Update values based on provided options
29 setOptions(options);
30}
31
32template <typename T>
33std::string_view TrustRegionQRT<T>::getName() const {
34 return "TrustRegionQR";
35}
36
37template <typename T>
39 this->curTrustRegionRadius_ = this->trustRegionRadius_;
40}
41
42template <typename T>
45
46 if (const auto* derivedOptions = dynamic_cast<const TrustRegionQROptions*>(&options)) {
47 this->trustRegionRadius_ = derivedOptions->trustRegionRadius_;
48 }
49}
50
51template <typename T>
54
55 const auto sf = static_cast<SkeletonSolverFunctionT<T>*>(this->solverFunction_);
56
57 const auto skeleton = sf->getSkeleton();
58 const auto parameterTransform = sf->getParameterTransform();
59
60 {
61 MT_PROFILE_EVENT("JtJR - update state");
62 skeletonState_.set(parameterTransform->apply(this->parameters_), *skeleton);
63 }
64
65 if (sf->needsMeshState()) {
66 MT_PROFILE_EVENT("JtJR - update mesh state");
67 meshState_.update(this->parameters_, skeletonState_, sf->getCharacter());
68 }
69
70 const auto nFullParams = gsl::narrow_cast<Eigen::Index>(this->parameters_.size());
71
72 std::vector<Eigen::Index> enabledParameters;
73 enabledParameters.reserve(nFullParams);
74 for (Eigen::Index iFullParam = 0; iFullParam < nFullParams; ++iFullParam) {
75 if (this->activeParameters_.test(iFullParam)) {
76 enabledParameters.push_back(iFullParam);
77 }
78 }
79
80 const auto nSubsetParams = gsl::narrow_cast<Eigen::Index>(enabledParameters.size());
81
82 // Add a tiny lambda just to make sure we don't divide by zero when back-substituting into R,
83 // this isn't intended to regularize the problem at all (searching for the actual lambda parameter
84 // that respects the trust region radius happens below).
85 T lambda = 1e-10;
86 this->qrSolver_.reset(nSubsetParams, lambda);
87
88 // Compute the QR factorization of the Jacobian:
89 double error_orig = 0.0;
90 for (const auto& errorFunction : sf->getErrorFunctions()) {
91 if (errorFunction->getWeight() <= 0) {
92 continue;
93 }
94
95 const auto rows = padToSimdAlignment(errorFunction->getJacobianSize());
96
97 jacobian_.resizeAndSetZero(rows, nFullParams);
98 residual_.resizeAndSetZero(rows);
99
100 int usedRows = 0;
101 error_orig += errorFunction->getJacobian(
102 this->parameters_, skeletonState_, meshState_, jacobian_.mat(), residual_.mat(), usedRows);
103 if (usedRows == 0) {
104 continue;
105 }
106
107 this->qrSolver_.addMutating(
108 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
109 jacobian_.mat().topRows(usedRows), enabledParameters),
110 residual_.mat().topRows(usedRows));
111 }
112
113 this->error_ = error_orig;
114
115 // Because the error function is computed r^t*r, the gradient is
116 // 2*J^T*r.
117 this->gradientSub_ = T(2) * qrSolver_.At_times_b();
118
119 // Save the R matrix before we start adding lambdas:
120 this->Rmatrix_ = this->qrSolver_.R();
121
122 // The Hessian is approximated by 2*J^T*J.
123 // In the QR solver, we compute J = Q*R.
124 // 2*J^T*J = (Q*R)^T * (Q*R)
125 // = R^T * Q^T * Q * R
126 // = 2 * R^T * R
127 // To compute v^T * H * v, we can then compute
128 // 2 * ||R * v||^2
129
130 // This is the local approximation to the function used in the trust region solve:
131 auto evalQuadraticModel = [&](Eigen::Ref<const Eigen::VectorX<T>> p) -> T {
132 T result = this->error_;
133 result -= this->gradientSub_.dot(p);
134 // Normally in textbooks you'd see this multiplied by 1/2 for the proper Taylor series
135 // expansion but remember that our Hessian is actually 2*J^T*J:
136 result += (this->Rmatrix_.template triangularView<Eigen::Upper>() * p).squaredNorm();
137 return result;
138 };
139
140 auto subsetToFullVector = [&](Eigen::Ref<const Eigen::VectorX<T>> v_subset) -> Eigen::VectorX<T> {
141 Eigen::VectorX<T> result = Eigen::VectorX<T>::Zero(nFullParams);
142 for (Eigen::Index iSubsetParam = 0; iSubsetParam < nSubsetParams; ++iSubsetParam) {
143 const Eigen::Index iFullParam = enabledParameters[iSubsetParam];
144 result[iFullParam] = v_subset[iSubsetParam];
145 }
146 return result;
147 };
148
149 // TODO what is a good value for nu?
150 const T nu = 0;
151
152 for (size_t iTrustStep = 0; iTrustStep < 10; ++iTrustStep) {
153 Eigen::VectorX<T> searchDir_sub = this->qrSolver_.result();
154
155 // If even our most optimistic guess of how much we can decrease the error
156 // suggests that it's not going to change by a measurable amount (FLT_EPS times its current
157 // value), then stop trying to iterate. If we don't do that we run into issues below where the
158 // rho value is just capturing noise and our trust region will drop to 0.
159 if (searchDir_sub.dot(gradientSub_) < FLT_EPSILON * (T(1.0) + this->error_)) {
160 break;
161 }
162
163 // We use a standard Newton approach for quickly converging to the lambda that limits
164 // the step size to the trust region. This is described in section 4.3 of Nocedal/Wright,
165 // "Iterative solution of the subproblem."
166 //
167 // We will only allow the value of lambda to _increase_, which corresponds to shrinking the
168 // trust region. That is, we start with a trust region that is too large, and then we
169 // iteratively shrink it until it's close enough to the desired delta. This is because (1) in
170 // practice, this is what seems to happen anyways, given that we start from 0 and (2) it's a lot
171 // easier to add to lambda than subtract from lambda; the former can always be done by just
172 // adding some additional rows to the Jacobian while the latter requires "backing out" to a
173 // previous version of the QR solver. This is okay because it's always more acceptable (within
174 // reason) to take a too-small step than a too-large one:
175 for (size_t iIter = 0; iIter < 3; ++iIter) {
176 if (searchDir_sub.norm() < T(1.05) * this->curTrustRegionRadius_) {
177 break;
178 }
179
180 const Eigen::MatrixX<T>& Rmat = this->qrSolver_.R();
181 // This is equation 4.44 in Nocedal/Wright. Note that our error function is actually
182 // r^T*r which means gradientSub_ is 2*J^T*r, but the Hessian approximated inside the QR
183 // solver is J^T*J. Since we're applying the lambda within the QR solver also, we'll stay
184 // consistent with the J^T*J/J^T*r version of the world and multiply our gradientSub_ by 0.5
185 // on its way in.
186 Eigen::VectorX<T> p_l = Rmat.template triangularView<Eigen::Upper>().solve(
187 Rmat.template triangularView<Eigen::Upper>().transpose().solve(-T(0.5) * gradientSub_));
188 Eigen::VectorX<T> q_l = Rmat.template triangularView<Eigen::Upper>().transpose().solve(p_l);
189
190 const T p_l_norm2 = p_l.squaredNorm();
191 const T q_l_norm2 = q_l.squaredNorm();
192
193 if (q_l_norm2 < FLT_EPSILON) {
194 break;
195 }
196
197 const T p_l_norm = std::sqrt(p_l_norm2);
198 const T deltaLambda = (p_l_norm2 / q_l_norm2) *
199 ((p_l_norm - this->curTrustRegionRadius_) / (this->curTrustRegionRadius_));
200
201 // We can only easily _increase_ the lambda value, so stop if the change is negative:
202 if (deltaLambda <= 0) {
203 break;
204 }
205
206 {
207 // We want to find a y such that:
208 // lambda + y^2 = (lambda + deltaLambda)
209 // y = sqrt((lambda + deltaLambda) - lambda)
210 const T lambdaNew = lambda + deltaLambda;
211 const T y = std::sqrt(lambdaNew - lambda);
212
213 // Add the lambda terms:
214 // TODO make this faster than O(n^2):
215 this->lambdaDiag_.resize(nSubsetParams, nSubsetParams);
216 this->lambdaDiag_.setZero();
217 this->lambdaDiag_.diagonal().setConstant(y);
218
219 this->lambdaZero_.resize(nSubsetParams);
220 this->lambdaZero_.setZero();
221
222 this->qrSolver_.addMutating(this->lambdaDiag_, this->lambdaZero_);
223
224 lambda = lambdaNew;
225 }
226
227 searchDir_sub = this->qrSolver_.result();
228
230 this->verbose_,
231 " Iter: {}; Search dir cur norm: {}; delta: {}; lambda: {}",
232 iIter,
233 searchDir_sub.norm(),
234 this->curTrustRegionRadius_,
235 lambda);
236 }
237
238 const Eigen::VectorX<T> parameters_orig = this->parameters_;
239 this->solverFunction_->updateParameters(this->parameters_, subsetToFullVector(searchDir_sub));
240 const double error_new = this->solverFunction_->getError(this->parameters_);
241
242 // This is the decrease of the function relative to what we _expected_ the function to
243 // decrease by. It is eq. 4.4 in Nocedal and Wright.
244 const T quadraticModelEval = evalQuadraticModel(searchDir_sub);
245 const T rho = (this->error_ - error_new) / (this->error_ - quadraticModelEval);
247 this->verbose_,
248 "Error orig: {}; error new: {}; quadratic model: {}; rho: {}",
249 this->error_,
250 error_new,
251 quadraticModelEval,
252 rho);
253
254 if (rho < T(0.25)) {
255 // Model is no good, decrease the radius:
256 this->curTrustRegionRadius_ = T(0.25) * this->curTrustRegionRadius_;
257 } else if (rho > T(0.75) && lambda > 0) {
258 // Model seems good and we're pushing up against the trust region boundary, so increase it:
259 this->curTrustRegionRadius_ =
260 std::min(T(2) * this->curTrustRegionRadius_, this->maxTrustRegionRadius_);
261 }
262
263 if (rho > nu) {
264 break;
265 } else {
266 // Reject the step, reduce the trust region size and try again:
267 this->parameters_ = parameters_orig;
268 }
269 }
270}
271
272template class TrustRegionQRT<float>;
273template class TrustRegionQRT<double>;
274
275} // namespace momentum
View over a matrix that exposes a (possibly reordered) subset of its columns.
const Skeleton * getSkeleton() const
Legacy compatibility (delegates to character_.skeleton).
virtual void setOptions(const SolverOptions &options)
Updates solver configuration with new options.
Definition solver.cpp:32
ParameterSet activeParameters_
Bitset indicating which parameters are enabled for optimization.
Definition solver.h:112
Eigen::VectorX< T > parameters_
Current parameter values.
Definition solver.h:109
bool verbose_
Whether to output detailed progress information.
Definition solver.h:142
double error_
Current objective function value.
Definition solver.h:126
SolverFunctionT< T > * solverFunction_
Function to be optimized.
Definition solver.h:106
SolverT(const SolverOptions &options, SolverFunctionT< T > *solver)
Constructor with solver options and function to optimize.
Definition solver.cpp:20
void setOptions(const SolverOptions &options) final
Updates solver configuration with new options.
std::string_view getName() const override
Returns the name of the solver implementation.
TrustRegionQRT(const SolverOptions &options, SkeletonSolverFunctionT< T > *solverFun)
void doIteration() final
Performs a single iteration of the optimization algorithm.
void initializeSolver() final
Initializes solver state before optimization begins.
#define MT_LOGI_IF(condition,...)
Definition log.h:185
constexpr size_t padToSimdAlignment(size_t size)
Pads a row count to be a multiple of kJacobianRowAlignment for SIMD alignment.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_EVENT(NAME)
Definition profile.h:112
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
Common options for numerical optimization solvers.
Definition solver.h:19
Trust Region with QR decomposition specific options.
float trustRegionRadius_
Trust region radius parameter for the Trust Region solver with QR decomposition.