Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
sequence_solver.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
17#include "momentum/common/log.h"
22
23#include <dispenso/parallel_for.h>
24
25#include <mutex>
26
27namespace momentum {
28
29template <typename T>
31 const SolverOptions& options,
33 : SequenceSolverBaseT<T>(options, function) {
34 setOptions(options);
35}
36
37template <typename T>
38std::string_view SequenceSolverT<T>::getName() const {
39 return "SequenceSolver";
40}
41
42template <typename T>
46
47template <typename T>
50
51 auto* fn = dynamic_cast<SequenceSolverFunctionT<T>*>(this->solverFunction_);
52 MT_CHECK(fn != nullptr);
53
54 this->bandwidth_ = 1;
55 for (const auto& frameErrf : fn->sequenceErrorFunctions_) {
56 for (const auto& errf : frameErrf) {
57 this->bandwidth_ = std::max(this->bandwidth_, errf->numFrames());
58 }
59 }
60}
61
62// Compute the full per-frame Jacobian and update the skeleton state:
63template <typename T>
64typename SequenceSolverT<T>::JacobianResidual SequenceSolverT<T>::computePerFrameJacobian(
66 size_t iFrame,
67 SkeletonStateT<T>& skelState,
68 MeshStateT<T>& meshState) {
69 const auto& frameParameters = fn->frameParameters_[iFrame];
70
71 const auto& character = fn->getCharacter();
72
73 skelState.set(fn->parameterTransform_.apply(frameParameters), character.skeleton);
74
75 if (fn->needsMeshPerFrame()) {
76 meshState.update(frameParameters, skelState, character);
77 }
78
79 const auto nFullParameters = fn->parameterTransform_.numAllModelParameters();
80 const auto jacobianSize =
81 padToSimdAlignment(detail::computeJacobianSize(fn->perFrameErrorFunctions_[iFrame]));
82 Eigen::MatrixX<T> jacobian = Eigen::MatrixX<T>::Zero(jacobianSize, nFullParameters);
83 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
84
85 Eigen::Index offset = 0;
86 double errorCur = 0;
87 for (const auto& errf : fn->perFrameErrorFunctions_[iFrame]) {
88 if (errf->getWeight() <= 0.0f) {
89 continue;
90 }
91
92 const auto n = errf->getJacobianSize();
93
94 int rows = 0;
95 errorCur += errf->getJacobian(
96 frameParameters,
97 skelState,
98 meshState,
99 jacobian.block(offset, 0, n, nFullParameters),
100 residual.middleRows(offset, n),
101 rows);
102
103 MT_CHECK(rows >= 0 && rows <= static_cast<Eigen::Index>(n));
104
105 offset += rows;
106 }
107
108 return {
109 .frameIndex = iFrame,
110 .jacobian = std::move(jacobian),
111 .residual = std::move(residual),
112 .error = errorCur,
113 .nFunctions = fn->perFrameErrorFunctions_[iFrame].size(),
114 .usedRows = offset};
115}
116
117template <typename T>
118typename SequenceSolverT<T>::JacobianResidual SequenceSolverT<T>::computeSequenceJacobian(
120 size_t iFrame,
121 size_t bandwidth,
122 std::span<const SkeletonStateT<T>> skelStates,
123 std::span<const MeshStateT<T>> meshStates) {
124 const size_t bandwidth_cur = std::min(fn->getNumFrames() - iFrame, bandwidth);
125 MT_CHECK(skelStates.size() >= bandwidth_cur);
126 MT_CHECK(meshStates.size() >= bandwidth_cur);
127
128 const auto nFullParameters = fn->parameterTransform_.numAllModelParameters();
129 const size_t jacobianSize =
130 padToSimdAlignment(detail::computeJacobianSize(fn->sequenceErrorFunctions_[iFrame]));
131 Eigen::MatrixX<T> jacobian =
132 Eigen::MatrixX<T>::Zero(jacobianSize, bandwidth_cur * nFullParameters);
133 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
134
135 Eigen::Index offset = 0;
136 double errorCur = 0;
137 for (const auto& errf : fn->sequenceErrorFunctions_[iFrame]) {
138 if (errf->getWeight() <= 0.0f) {
139 continue;
140 }
141
142 const auto nFrames = errf->numFrames();
143 MT_CHECK(nFrames <= bandwidth_cur);
144 const size_t n = errf->getJacobianSize();
145 int rows = 0;
146 errorCur += errf->getJacobian(
147 std::span(fn->frameParameters_).subspan(iFrame, nFrames),
148 skelStates.subspan(0, nFrames),
149 meshStates.subspan(0, nFrames),
150 jacobian.block(offset, 0, n, nFrames * nFullParameters),
151 residual.middleRows(offset, n),
152 rows);
153
154 MT_CHECK(rows >= 0 && rows <= static_cast<Eigen::Index>(n));
155 offset += rows;
156 }
157
158 // Because we have only one copy of the universal parameters, we need to merge all the
159 // per-frame Jacobians into the first block.
160 for (size_t iUnivParam = 0; iUnivParam < fn->universalParameterIndices_.size(); ++iUnivParam) {
161 for (size_t kSubFrame = 1; kSubFrame < bandwidth_cur; ++kSubFrame) {
162 jacobian.col(fn->universalParameterIndices_[iUnivParam]) +=
163 jacobian.col(kSubFrame * nFullParameters + fn->universalParameterIndices_[iUnivParam]);
164 }
165 }
166
167 return {
168 .frameIndex = iFrame,
169 .jacobian = std::move(jacobian),
170 .residual = std::move(residual),
171 .error = errorCur,
172 .nFunctions = fn->sequenceErrorFunctions_[iFrame].size(),
173 .usedRows = offset};
174}
175
176template <typename T>
177double SequenceSolverT<T>::processPerFrameErrors_serial(
180 ProgressBar* progress) {
181 SkeletonStateT<T> skelState;
182 MeshStateT<T> meshState;
183 double errorSum = 0;
184 for (size_t iFrame = 0; iFrame < fn->getNumFrames(); ++iFrame) {
185 auto jacRes = computePerFrameJacobian(fn, iFrame, skelState, meshState);
186 errorSum += jacRes.error;
187
188 if (jacRes.usedRows > 0) {
189 qrSolver.addMutating(
190 iFrame * fn->perFrameParameterIndices_.size(),
191 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
192 jacRes.jacobian.topRows(jacRes.usedRows), fn->perFrameParameterIndices_),
193 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
194 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
195 jacRes.residual.topRows(jacRes.usedRows));
196 }
197
198 if (progress) {
199 progress->increment(jacRes.nFunctions);
200 }
201 }
202 return errorSum;
203}
204
205namespace {
206
207template <typename T, typename Comparator>
208class PriorityQueue {
209 public:
210 void push(T value) {
211 queue.push_back(std::move(value));
212 std::push_heap(queue.begin(), queue.end(), Comparator());
213 }
214
215 void pop() {
216 std::pop_heap(queue.begin(), queue.end(), Comparator());
217 queue.pop_back();
218 }
219
220 [[nodiscard]] T& top() {
221 return queue.front();
222 }
223
224 [[nodiscard]] bool empty() const {
225 return queue.empty();
226 }
227
228 private:
229 std::vector<T> queue;
230};
231
232} // namespace
233
234template <typename T>
235double SequenceSolverT<T>::processErrorFunctions_parallel(
236 const std::function<JacobianResidual(
237 size_t,
241 MeshStateT<T>&)>& processJac,
244 ProgressBar* progress) {
245 const size_t end = fn->getNumFrames();
246
247 // We will buffer at the end of the pipeline to ensure the universal parts of the matrices are
248 // always processed in the same order; this will make it deterministic and simplify debugging.
249 PriorityQueue<JacobianResidual, std::greater<>> reorderBuffer;
250 std::mutex reorderBufferMutex;
251
252 std::deque<JacobianResidual> readyJacobians;
253 std::mutex readyJacobiansMutex;
254 std::size_t nextToProcess{0};
255
256 // Mutex to lock access to the universal part of the matrix.
257 double errorSum = 0;
258 std::mutex qrSolverMutex;
259
260 // The way this pipeline works is:
261 // 1. We compute the full Jacobian/residual for each from each frame.
262 // 2. We zero out the non-shared parts of the Jacobian in parallel
263 // 3. We zero out the shared parts of the Jacobian serially in order in the last stage.
264 std::vector<PerFrameStateT<T>> states;
265 dispenso::parallel_for(
266 states,
267 []() -> PerFrameStateT<T> { return PerFrameStateT<T>(); },
268 dispenso::makeChunkedRange(0, end, 1),
269 [&](PerFrameStateT<T>& state, size_t rangeStart, size_t rangeEnd) {
270 for (size_t iFrame = rangeStart; iFrame < rangeEnd; ++iFrame) {
271 if (iFrame >= end) {
272 // nothing to do:
273 return;
274 }
275
276 JacobianResidual universalJacRes =
277 processJac(iFrame, fn, qrSolver, state.skeletonState, state.meshState);
278
279 // Need to push into the queue:
280 std::unique_lock<std::mutex> reorderBufferLock(reorderBufferMutex);
281 reorderBuffer.push(std::move(universalJacRes));
282
283 // Move any Jacobians that are "ready" out of the reorder buffer and into the
284 // "up-next" queue.
285 while (!reorderBuffer.empty() && reorderBuffer.top().frameIndex == nextToProcess) {
286 {
287 std::unique_lock<std::mutex> readyJacobiansLock(readyJacobiansMutex);
288 readyJacobians.push_back(std::move(reorderBuffer.top()));
289 }
290 nextToProcess++;
291 reorderBuffer.pop();
292 }
293 }
294
295 // Now maybe drain the queue:
296 std::unique_lock<std::mutex> qrSolverLock(qrSolverMutex, std::try_to_lock);
297 if (qrSolverLock.owns_lock()) {
298 while (true) {
299 JacobianResidual toProcess;
300 {
301 std::unique_lock<std::mutex> lock(readyJacobiansMutex);
302 if (!readyJacobians.empty()) {
303 toProcess = std::move(readyJacobians.front());
304 readyJacobians.pop_front();
305 }
306 }
307
308 MT_CHECK(toProcess.usedRows <= toProcess.residual.rows());
309
310 if (toProcess.frameIndex == SIZE_MAX) {
311 break;
312 } else {
313 if (toProcess.residual.rows() > 0) {
314 qrSolver.addMutating(
315 toProcess.jacobian.topRows(toProcess.usedRows),
316 toProcess.residual.topRows(toProcess.usedRows));
317 }
318 errorSum += toProcess.error;
319 if (progress) {
320 progress->increment(toProcess.nFunctions);
321 }
322 }
323 }
324 }
325 });
326
327 // Drain the rest of the queue:
328 {
329 std::unique_lock<std::mutex> solverLock(qrSolverMutex);
330
331 {
332 std::unique_lock<std::mutex> reorderLock(readyJacobiansMutex);
333 while (!readyJacobians.empty()) {
334 if (readyJacobians.front().usedRows > 0) {
335 qrSolver.addMutating(
336 readyJacobians.front().jacobian.topRows(readyJacobians.front().usedRows),
337 readyJacobians.front().residual.topRows(readyJacobians.front().usedRows));
338 }
339 errorSum += readyJacobians.front().error;
340 if (progress) {
341 progress->increment(readyJacobians.front().nFunctions);
342 }
343 readyJacobians.pop_front();
344 }
345 }
346
347 {
348 std::unique_lock<std::mutex> reorderLock(reorderBufferMutex);
349 while (!reorderBuffer.empty()) {
350 if (reorderBuffer.top().usedRows > 0) {
351 qrSolver.addMutating(
352 reorderBuffer.top().jacobian.topRows(reorderBuffer.top().usedRows),
353 reorderBuffer.top().residual.topRows(reorderBuffer.top().usedRows));
354 }
355 errorSum += reorderBuffer.top().error;
356 if (progress) {
357 progress->increment(reorderBuffer.top().nFunctions);
358 }
359 reorderBuffer.pop();
360 }
361 }
362 }
363
364 return errorSum;
365}
366
367// Process the per-frame error functions that lie along the diagonal:
368template <typename T>
369double SequenceSolverT<T>::processPerFrameErrors_parallel(
372 ProgressBar* progress) {
373 return processErrorFunctions_parallel(
374 [](size_t iFrame,
377 SkeletonStateT<T> skelState,
378 MeshStateT<T>& meshState) -> JacobianResidual {
379 // Construct the Jacobian/residual for a single frame and zero out the parts
380 // of the Jacobian that only affect that frame; this is safe to do because
381 // the non-shared parameters for each frame don't overlap.
382 auto jacRes = computePerFrameJacobian(fn, iFrame, skelState, meshState);
383
384 if (jacRes.usedRows > 0) {
385 qrSolver.zeroBandedPart(
386 iFrame * fn->perFrameParameterIndices_.size(),
387 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
388 jacRes.jacobian.topRows(jacRes.usedRows), fn->perFrameParameterIndices_),
389 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
390 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
391 jacRes.residual.topRows(jacRes.usedRows));
392 }
393
394 if (fn->universalParameterIndices_.empty()) {
395 // Optimization: don't hang onto the residual if we aren't going to need it later.
396 return {
397 .frameIndex = iFrame,
398 .jacobian = Eigen::MatrixX<T>(),
399 .residual = Eigen::VectorX<T>(),
400 .error = jacRes.error,
401 .nFunctions = jacRes.nFunctions,
402 .usedRows = 0};
403 } else {
404 // Now, pass the Jacobian/residual pair for the universal parameters to be handled by the
405 // last stage. These Jacobians must be handled one at a time because the universal
406 // parameters are shared between all frames.
407 return {
408 .frameIndex = iFrame,
409 .jacobian = jacRes.jacobian.topRows(jacRes.usedRows)(
410 Eigen::indexing::all, fn->universalParameterIndices_),
411 .residual = jacRes.residual.topRows(jacRes.usedRows),
412 .error = jacRes.error,
413 .nFunctions = jacRes.nFunctions,
414 .usedRows = jacRes.usedRows};
415 }
416 },
417 fn,
418 qrSolver,
419 progress);
420}
421
422// Process the "sequence" error functions that span multiple frames:
423template <typename T>
424double SequenceSolverT<T>::processSequenceErrors_serial(
427 ProgressBar* progress) {
428 if (fn->numTotalSequenceErrorFunctions_ == 0) {
429 return 0;
430 }
431
432 const size_t bandwidth = qrSolver.bandwidth() / fn->perFrameParameterIndices_.size();
433 MT_CHECK(qrSolver.bandwidth() % fn->perFrameParameterIndices_.size() == 0);
434
435 // Our per-frame matrices our now (bandwidth) frames wide, so we need (bandwidth)
436 // copies of the perFrameParameterIndices_:
437 const auto sequenceColumnIndices = detail::buildSequenceColumnIndices(fn, bandwidth);
438
439 std::vector<SkeletonStateT<T>> skelStates(bandwidth);
440 std::vector<MeshStateT<T>> meshStates(bandwidth);
441
442 double errorSum = 0;
443 for (size_t iFrame = 0; iFrame < fn->getNumFrames(); ++iFrame) {
444 const size_t bandwidth_cur = std::min<size_t>(fn->getNumFrames() - iFrame, bandwidth);
445
446 // Determine how many frames are already valid from the previous iteration
447 // First frame: 0 (compute all), subsequent frames: bandwidth_cur - 1 (reuse all but last)
448 const size_t numValidFrames = (iFrame == 0) ? 0 : (bandwidth_cur - 1);
449
450 // Shift valid frames left by 1 to reuse already-computed states
451 for (size_t kSubFrame = 0; kSubFrame < numValidFrames; ++kSubFrame) {
452 skelStates[kSubFrame] = std::move(skelStates[kSubFrame + 1]);
453 if (fn->needsMeshSequence()) {
454 meshStates[kSubFrame] = std::move(meshStates[kSubFrame + 1]);
455 }
456 }
457
458 // Compute new frames (all frames if iFrame == 0, or just the last frame if iFrame > 0)
459 for (size_t kSubFrame = numValidFrames; kSubFrame < bandwidth_cur; ++kSubFrame) {
460 skelStates[kSubFrame].set(
461 fn->parameterTransform_.apply(fn->frameParameters_[iFrame + kSubFrame]),
462 fn->getCharacter().skeleton);
463
464 if (fn->needsMeshSequence()) {
465 meshStates[kSubFrame].update(
466 fn->frameParameters_[iFrame + kSubFrame], skelStates[kSubFrame], fn->getCharacter());
467 }
468 }
469
470 auto jacRes = computeSequenceJacobian(fn, iFrame, bandwidth, skelStates, meshStates);
471 errorSum += jacRes.error;
472
473 if (jacRes.usedRows > 0) {
474 qrSolver.addMutating(
475 iFrame * fn->perFrameParameterIndices_.size(),
476 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
477 jacRes.jacobian.topRows(jacRes.usedRows),
478 std::span(sequenceColumnIndices)
479 .subspan(0, bandwidth_cur * fn->perFrameParameterIndices_.size())),
480 ColumnIndexedMatrix<Eigen::MatrixX<T>>(
481 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
482 jacRes.residual.topRows(jacRes.usedRows));
483 }
484
485 if (progress) {
486 progress->increment(jacRes.nFunctions);
487 }
488 }
489 return errorSum;
490}
491
492template <typename T>
495
496 auto* fn = dynamic_cast<SequenceSolverFunctionT<T>*>(this->solverFunction_);
497 MT_CHECK(fn != nullptr);
498
500 fn->getNumFrames() * fn->perFrameParameterIndices_.size(),
501 fn->universalParameterIndices_.size(),
502 this->bandwidth_ * fn->perFrameParameterIndices_.size(),
503 std::sqrt(this->regularization_));
504
505 fn->setFrameParametersFromJoinedParameterVector(this->parameters_);
506
507 std::unique_ptr<ProgressBar> progress;
508 if (this->progressBar_) {
509 progress = std::make_unique<ProgressBar>(
510 "Solving sequence",
511 fn->numTotalPerFrameErrorFunctions_ + fn->numTotalSequenceErrorFunctions_);
512 }
513
514 this->error_ = 0;
515 if (this->multithreaded_) {
516 this->error_ += processPerFrameErrors_parallel(fn, qrSolver, progress.get());
517
518 // Sequence errors still have to be be processed serially, at least for now.
519 this->error_ += processSequenceErrors_serial(fn, qrSolver, progress.get());
520 } else {
521 this->error_ += processPerFrameErrors_serial(fn, qrSolver, progress.get());
522 this->error_ += processSequenceErrors_serial(fn, qrSolver, progress.get());
523 }
524
525 // Now, extract the delta:
526 const Eigen::VectorX<T> searchDir = qrSolver.x_dense();
527
528 const double error_orig = this->error_;
529 if (this->doLineSearch_) {
530 const double innerProd = -qrSolver.At_times_b().dot(searchDir);
531
532 // Line search:
533 const float c_1 = 1e-4f;
534 const float tau = 0.5f;
535 float alpha = 1.0f;
536
537 const Eigen::VectorX<T> parameters_orig = this->parameters_;
538 for (size_t kStep = 0; kStep < 10 && std::fpclassify(alpha) == FP_NORMAL; ++kStep) {
539 // update the this->parameters_
540 this->parameters_ = parameters_orig;
541 this->solverFunction_->updateParameters(this->parameters_, alpha * searchDir);
542
543 const double error_new = this->solverFunction_->getError(this->parameters_);
544
545 if ((error_orig - error_new) >= c_1 * alpha * -innerProd) {
546 break;
547 }
548
549 // Reduce step size:
550 alpha = alpha * tau;
551 }
552 } else {
553 this->solverFunction_->updateParameters(this->parameters_, searchDir);
554 }
555}
556
557template class SequenceSolverT<float>;
558template class SequenceSolverT<double>;
559
560} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
View over a matrix that exposes a (possibly reordered) subset of its columns.
Online Householder QR solver for band-plus-arrowhead matrices.
VectorType x_dense() const
Retrieves the full dense result vector of length n_band() + n_common().
A terminal progress bar rendered as Name [===> ] 60%.
SequenceSolverBaseT(const SolverOptions &options, SequenceSolverFunctionT< T > *function)
void setOptions(const SolverOptions &options) override
Updates solver configuration with new options.
bool needsMeshPerFrame() const
Returns whether the per-frame error functions need the mesh.
void initializeSolver() final
Initializes solver state before optimization begins.
SequenceSolverT(const SolverOptions &options, SequenceSolverFunctionT< T > *function)
std::string_view getName() const override
Returns the name of the solver implementation.
void doIteration() final
Performs a single iteration of the optimization algorithm.
void setOptions(const SolverOptions &options) final
Updates solver configuration with new options.
Eigen::VectorX< T > parameters_
Current parameter values.
Definition solver.h:109
double error_
Current objective function value.
Definition solver.h:126
SolverFunctionT< T > * solverFunction_
Function to be optimized.
Definition solver.h:106
size_t computeJacobianSize(const std::vector< std::shared_ptr< ErrorFunctionType > > &functions)
std::vector< Eigen::Index > buildSequenceColumnIndices(const SequenceSolverFunctionT< T > *fn, size_t bandwidth)
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_FUNCTION()
Definition profile.h:110
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.
Represents the complete state of a skeleton.
void set(const JointParametersT< T > &jointParameters, const Skeleton &referenceSkeleton, bool computeDeriv=true)
Updates the skeleton state with new joint parameters.
Common options for numerical optimization solvers.
Definition solver.h:19