Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
sequence_cholesky_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
18#include "momentum/common/log.h"
21
22#include <dispenso/parallel_for.h>
23#include <dispenso/thread_pool.h>
24
25#include <Eigen/Cholesky>
26
27#include <algorithm>
28#include <chrono>
29#include <cmath>
30#include <deque>
31#include <limits>
32#include <memory>
33#include <span>
34#include <type_traits>
35#include <vector>
36
37namespace momentum {
38
39namespace {
40
41template <typename T>
42struct JacobianResidual {
43 Eigen::MatrixX<T> jacobian;
44 Eigen::VectorX<T> residual;
45 double error = 0.0;
46 size_t nFunctions = 0;
47 Eigen::Index usedRows = 0;
48 Eigen::Index nBandColumns = 0;
49 size_t nFrameColumns = 0;
50};
51
52enum class SequenceJacobianSelection { All, InternalToChunk, CrossesChunk };
53
54template <typename T>
55bool useSequenceErrorFunction(
56 const SequenceErrorFunctionT<T>& errf,
57 size_t iFrame,
58 size_t chunkEnd,
59 SequenceJacobianSelection selection) {
60 switch (selection) {
61 case SequenceJacobianSelection::All:
62 return true;
63 case SequenceJacobianSelection::InternalToChunk:
64 return iFrame + errf.numFrames() <= chunkEnd;
65 case SequenceJacobianSelection::CrossesChunk:
66 return iFrame + errf.numFrames() > chunkEnd;
67 }
68 MT_THROW("Unhandled sequence Jacobian selection");
69}
70
71template <typename T>
72class NormalEquationBlock {
73 public:
74 using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
75 using VectorType = Eigen::Matrix<T, Eigen::Dynamic, 1>;
76
77 NormalEquationBlock(
78 Eigen::Index iColOffset,
79 Eigen::Index nBand,
80 Eigen::Index nCommon,
81 Eigen::Index bandwidth,
82 T regularization,
83 Eigen::Index blockSize = 1)
84 : iColOffset_(iColOffset),
85 nBand_(nBand),
86 bandwidth_(bandwidth),
87 blockSize_(blockSize),
88 common_(MatrixType::Zero(nBand + nCommon, nCommon)),
89 rhs_(VectorType::Zero(nBand + nCommon)) {
90 MT_CHECK(nBand == 0 || bandwidth > 0);
91 if (blockSize_ > 1 && nBand > 0 && nBand % blockSize_ == 0 && bandwidth % blockSize_ == 0) {
92 blockBandwidth_ = (bandwidth - 1) / blockSize_ + 1;
93 blockBand_ = MatrixType::Zero(nBand, blockBandwidth_ * blockSize_);
94 } else {
95 band_ = MatrixType::Zero(bandwidth, nBand);
96 }
97
98 if (hasBlockBand()) {
99 for (Eigen::Index iBlock = 0; iBlock < nBand / blockSize_; ++iBlock) {
100 blockBandBlock(iBlock, iBlock).diagonal().array() += regularization;
101 }
102 } else {
103 for (Eigen::Index iCol = 0; iCol < nBand; ++iCol) {
104 bandEntry(iCol, iCol) = regularization;
105 }
106 }
107 if (nCommon > 0) {
108 common_.bottomRightCorner(nCommon, nCommon).diagonal().setConstant(regularization);
109 }
110 }
111
112 [[nodiscard]] Eigen::Index iColOffset() const {
113 return iColOffset_;
114 }
115
116 [[nodiscard]] Eigen::Index nBand() const {
117 return nBand_;
118 }
119
120 [[nodiscard]] Eigen::Index nCommon() const {
121 return common_.cols();
122 }
123
124 [[nodiscard]] Eigen::Index bandwidth() const {
125 return bandwidth_;
126 }
127
128 [[nodiscard]] bool hasBlockBand() const {
129 return blockBandwidth_ > 0;
130 }
131
132 [[nodiscard]] Eigen::Index blockSize() const {
133 return blockSize_;
134 }
135
136 [[nodiscard]] Eigen::Index blockBandwidth() const {
137 return blockBandwidth_;
138 }
139
140 [[nodiscard]] const MatrixType& band() const {
141 return band_;
142 }
143
144 [[nodiscard]] const MatrixType& common() const {
145 return common_;
146 }
147
148 [[nodiscard]] const VectorType& rhs() const {
149 return rhs_;
150 }
151
152 MatrixType takeBlockBand() {
153 MT_CHECK(hasBlockBand());
154 return std::move(blockBand_);
155 }
156
157 auto blockBandBlock(Eigen::Index iBlock, Eigen::Index jBlock) {
158 MT_CHECK(hasBlockBand());
159 MT_CHECK(iBlock >= jBlock);
160 const Eigen::Index offset = iBlock - jBlock;
161 MT_CHECK(offset < blockBandwidth_);
162 return blockBand_.block(iBlock * blockSize_, offset * blockSize_, blockSize_, blockSize_);
163 }
164
165 [[nodiscard]] auto blockBandBlock(Eigen::Index iBlock, Eigen::Index jBlock) const {
166 MT_CHECK(hasBlockBand());
167 MT_CHECK(iBlock >= jBlock);
168 const Eigen::Index offset = iBlock - jBlock;
169 MT_CHECK(offset < blockBandwidth_);
170 return blockBand_.block(iBlock * blockSize_, offset * blockSize_, blockSize_, blockSize_);
171 }
172
173 [[nodiscard]] T bandEntry(Eigen::Index iRowLocal, Eigen::Index jColLocal) const {
174 MT_CHECK(iRowLocal <= jColLocal);
175 MT_CHECK(jColLocal - iRowLocal < bandwidth());
176 return band_(bandwidth() + iRowLocal - jColLocal - 1, jColLocal);
177 }
178
179 [[nodiscard]] T& bandEntry(Eigen::Index iRowLocal, Eigen::Index jColLocal) {
180 MT_CHECK(iRowLocal <= jColLocal);
181 MT_CHECK(jColLocal - iRowLocal < bandwidth());
182 return band_(bandwidth() + iRowLocal - jColLocal - 1, jColLocal);
183 }
184
185 template <typename JacobianDerived, typename ResidualDerived>
186 void add(
187 Eigen::Index iColOffset,
188 const Eigen::MatrixBase<JacobianDerived>& jacobian,
189 Eigen::Index nBandColumns,
190 const Eigen::MatrixBase<ResidualDerived>& residual,
191 size_t targetRowsPerJtJChunk) {
192 MT_CHECK(jacobian.rows() == residual.rows());
193 MT_CHECK(iColOffset >= iColOffset_);
194 MT_CHECK(iColOffset + nBandColumns <= iColOffset_ + nBand());
195 MT_CHECK(jacobian.cols() == nBandColumns + nCommon());
196
197 const Eigen::Index nCommonColumns = nCommon();
198 const Eigen::Index nRows = jacobian.rows();
199 const Eigen::Index rowChunkSize = static_cast<Eigen::Index>(
200 std::max<size_t>(1, std::min<size_t>(targetRowsPerJtJChunk, nRows)));
201 const Eigen::Index localBandOffset = iColOffset - iColOffset_;
202
203 for (Eigen::Index rowStart = 0; rowStart < nRows; rowStart += rowChunkSize) {
204 const Eigen::Index rowsCur = std::min(rowChunkSize, nRows - rowStart);
205 const MatrixType jacobianChunk =
206 jacobian.derived().middleRows(rowStart, rowsCur).template cast<T>();
207 const VectorType residualChunk =
208 residual.derived().segment(rowStart, rowsCur).template cast<T>();
209
210 const VectorType localRhs = jacobianChunk.transpose() * residualChunk;
211 rhs_.segment(localBandOffset, nBandColumns).noalias() += localRhs.head(nBandColumns);
212 if (nCommonColumns > 0) {
213 rhs_.tail(nCommonColumns).noalias() += localRhs.tail(nCommonColumns);
214 }
215
216 const MatrixType localHessian = jacobianChunk.transpose() * jacobianChunk;
217 if (nCommonColumns > 0) {
218 common_.middleRows(localBandOffset, nBandColumns).noalias() +=
219 localHessian.topRightCorner(nBandColumns, nCommonColumns);
220 common_.bottomRows(nCommonColumns).noalias() +=
221 localHessian.bottomRightCorner(nCommonColumns, nCommonColumns);
222 }
223
224 if (hasBlockBand() && localBandOffset % blockSize_ == 0 && nBandColumns % blockSize_ == 0) {
225 const Eigen::Index blockOffset = localBandOffset / blockSize_;
226 const Eigen::Index nBlocks = nBandColumns / blockSize_;
227 for (Eigen::Index iBlock = 0; iBlock < nBlocks; ++iBlock) {
228 for (Eigen::Index jBlock = 0; jBlock <= iBlock; ++jBlock) {
229 const Eigen::Index iGlobalBlock = blockOffset + iBlock;
230 const Eigen::Index jGlobalBlock = blockOffset + jBlock;
231 if (iGlobalBlock - jGlobalBlock >= blockBandwidth_) {
232 continue;
233 }
234 auto block = blockBandBlock(iGlobalBlock, jGlobalBlock);
235 for (Eigen::Index i = 0; i < blockSize_; ++i) {
236 for (Eigen::Index j = 0; j < blockSize_; ++j) {
237 const Eigen::Index iGlobal = iGlobalBlock * blockSize_ + i;
238 const Eigen::Index jGlobal = jGlobalBlock * blockSize_ + j;
239 if (std::abs(iGlobal - jGlobal) < bandwidth_) {
240 block(i, j) += localHessian(iBlock * blockSize_ + i, jBlock * blockSize_ + j);
241 }
242 }
243 }
244 }
245 }
246 } else {
247 for (Eigen::Index iBand = 0; iBand < nBandColumns; ++iBand) {
248 const Eigen::Index iLocal = localBandOffset + iBand;
249 for (Eigen::Index jBand = iBand; jBand < nBandColumns; ++jBand) {
250 const Eigen::Index jLocal = localBandOffset + jBand;
251 if (jLocal - iLocal >= bandwidth()) {
252 continue;
253 }
254 bandEntry(iLocal, jLocal) += localHessian(iBand, jBand);
255 }
256 }
257 }
258 }
259 }
260
261 void mergeBlock(const NormalEquationBlock& rhs) {
262 MT_CHECK(nCommon() == rhs.nCommon());
263 MT_CHECK(bandwidth() >= rhs.bandwidth());
264 MT_CHECK(rhs.iColOffset() >= iColOffset());
265 MT_CHECK(rhs.iColOffset() + rhs.nBand() <= iColOffset() + nBand());
266
267 const Eigen::Index localOffset = rhs.iColOffset() - iColOffset();
268 if (hasBlockBand() && rhs.hasBlockBand() && blockSize() == rhs.blockSize() &&
269 localOffset % blockSize_ == 0 && blockBandwidth() == rhs.blockBandwidth()) {
270 blockBand_.middleRows(localOffset, rhs.nBand()).noalias() += rhs.blockBand_;
271 } else {
272 for (Eigen::Index iCol = 0; iCol < rhs.nBand(); ++iCol) {
273 for (Eigen::Index iRow = std::max<Eigen::Index>(0, iCol - rhs.bandwidth() + 1);
274 iRow <= iCol;
275 ++iRow) {
276 bandEntry(localOffset + iRow, localOffset + iCol) += rhs.bandEntry(iRow, iCol);
277 }
278 }
279 }
280
281 if (rhs.nBand() > 0) {
282 if (nCommon() > 0) {
283 common_.middleRows(localOffset, rhs.nBand()).noalias() += rhs.common().topRows(rhs.nBand());
284 }
285 rhs_.segment(localOffset, rhs.nBand()).noalias() += rhs.rhs().head(rhs.nBand());
286 }
287 if (nCommon() > 0) {
288 common_.bottomRows(nCommon()).noalias() += rhs.common().bottomRows(rhs.nCommon());
289 rhs_.tail(nCommon()).noalias() += rhs.rhs().tail(rhs.nCommon());
290 }
291 }
292
293 private:
294 Eigen::Index iColOffset_ = 0;
295 Eigen::Index nBand_ = 0;
296 Eigen::Index bandwidth_ = 0;
297 Eigen::Index blockSize_ = 1;
298 Eigen::Index blockBandwidth_ = 0;
299 MatrixType band_;
300 MatrixType blockBand_;
301 MatrixType common_;
302 VectorType rhs_;
303};
304
305template <typename T>
306void computeState(
308 size_t iFrame,
309 bool needsMesh,
310 SkeletonStateT<T>& skelState,
311 MeshStateT<T>& meshState) {
312 skelState.set(
313 (*fn->getParameterTransform()).apply(fn->getFrameParameters()[iFrame]),
314 fn->getCharacter().skeleton);
315 if (needsMesh) {
316 meshState.update(fn->getFrameParameters()[iFrame], skelState, fn->getCharacter());
317 }
318}
319
320template <typename T>
321Eigen::MatrixX<T> compactJacobianColumns(
322 Eigen::Ref<const Eigen::MatrixX<T>> jacobian,
323 std::span<const Eigen::Index> bandColumnIndices,
324 std::span<const Eigen::Index> commonColumnIndices) {
325 Eigen::MatrixX<T> result(
326 jacobian.rows(),
327 static_cast<Eigen::Index>(bandColumnIndices.size() + commonColumnIndices.size()));
328 Eigen::Index iOut = 0;
329 for (const Eigen::Index iCol : bandColumnIndices) {
330 MT_CHECK(iCol >= 0 && iCol < jacobian.cols());
331 result.col(iOut++) = jacobian.col(iCol);
332 }
333 for (const Eigen::Index iCol : commonColumnIndices) {
334 MT_CHECK(iCol >= 0 && iCol < jacobian.cols());
335 result.col(iOut++) = jacobian.col(iCol);
336 }
337 return result;
338}
339
340template <typename T>
341JacobianResidual<T> computePerFrameJacobian(
343 size_t iFrame,
344 SkeletonStateT<T>& skelState,
345 MeshStateT<T>& meshState) {
346 computeState(fn, iFrame, fn->needsMeshPerFrame(), skelState, meshState);
347
348 const auto nFullParameters = (*fn->getParameterTransform()).numAllModelParameters();
349 const auto jacobianSize =
350 padToSimdAlignment(detail::computeJacobianSize(fn->getErrorFunctions()[iFrame]));
351 Eigen::MatrixX<T> jacobian = Eigen::MatrixX<T>::Zero(jacobianSize, nFullParameters);
352 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
353
354 Eigen::Index offset = 0;
355 double errorCur = 0;
356 for (const auto& errf : fn->getErrorFunctions()[iFrame]) {
357 if (errf->getWeight() <= 0.0f) {
358 continue;
359 }
360
361 const auto n = errf->getJacobianSize();
362
363 int rows = 0;
364 errorCur += errf->getJacobian(
365 fn->getFrameParameters()[iFrame],
366 skelState,
367 meshState,
368 jacobian.block(offset, 0, n, nFullParameters),
369 residual.middleRows(offset, n),
370 rows);
371
372 MT_CHECK(rows >= 0 && rows <= static_cast<Eigen::Index>(n));
373 offset += rows;
374 }
375
376 return {
377 .jacobian = compactJacobianColumns<T>(
378 jacobian.topRows(offset),
379 fn->getPerFrameParameterIndices(),
380 fn->getUniversalParameterIndices()),
381 .residual = std::move(residual),
382 .error = errorCur,
383 .nFunctions = fn->getErrorFunctions()[iFrame].size(),
384 .usedRows = offset,
385 .nBandColumns = static_cast<Eigen::Index>(fn->getPerFrameParameterIndices().size())};
386}
387
388template <typename T>
389JacobianResidual<T> computeSequenceJacobian(
391 size_t iFrame,
392 size_t bandwidth,
393 size_t chunkEnd,
394 SequenceJacobianSelection selection) {
395 const size_t maxBandwidthCur = std::min(fn->getNumFrames() - iFrame, bandwidth);
396 size_t bandwidthCur = 0;
397 size_t jacobianSizeRaw = 0;
398 size_t nSelectedFunctions = 0;
399 for (const auto& errf : fn->getSequenceErrorFunctions()[iFrame]) {
400 if (!useSequenceErrorFunction(*errf, iFrame, chunkEnd, selection)) {
401 continue;
402 }
403 ++nSelectedFunctions;
404 if (errf->getWeight() <= 0) {
405 continue;
406 }
407 bandwidthCur = std::max(bandwidthCur, errf->numFrames());
408 jacobianSizeRaw += errf->getJacobianSize();
409 }
410 MT_CHECK(bandwidthCur <= maxBandwidthCur);
411
412 if (bandwidthCur == 0) {
413 return {
414 .jacobian = Eigen::MatrixX<T>::Zero(
415 0, static_cast<Eigen::Index>(fn->getUniversalParameterIndices().size())),
416 .residual = Eigen::VectorX<T>::Zero(0),
417 .error = 0.0,
418 .nFunctions = nSelectedFunctions,
419 .usedRows = 0,
420 .nBandColumns = 0,
421 .nFrameColumns = 0};
422 }
423
424 std::vector<SkeletonStateT<T>> skelStates(bandwidthCur);
425 std::vector<MeshStateT<T>> meshStates(bandwidthCur);
426 for (size_t kSubFrame = 0; kSubFrame < bandwidthCur; ++kSubFrame) {
427 computeState(
428 fn,
429 iFrame + kSubFrame,
430 fn->needsMeshSequence(),
431 skelStates[kSubFrame],
432 meshStates[kSubFrame]);
433 }
434
435 const auto nFullParameters = (*fn->getParameterTransform()).numAllModelParameters();
436 const size_t jacobianSize = padToSimdAlignment(jacobianSizeRaw);
437 Eigen::MatrixX<T> jacobian =
438 Eigen::MatrixX<T>::Zero(jacobianSize, bandwidthCur * nFullParameters);
439 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
440
441 Eigen::Index offset = 0;
442 double errorCur = 0;
443 for (const auto& errf : fn->getSequenceErrorFunctions()[iFrame]) {
444 if (!useSequenceErrorFunction(*errf, iFrame, chunkEnd, selection)) {
445 continue;
446 }
447 if (errf->getWeight() <= 0.0f) {
448 continue;
449 }
450
451 const auto nFrames = errf->numFrames();
452 MT_CHECK(nFrames <= bandwidthCur);
453 const size_t n = errf->getJacobianSize();
454 int rows = 0;
455 errorCur += errf->getJacobian(
456 std::span(fn->getFrameParameters()).subspan(iFrame, nFrames),
457 std::span<const SkeletonStateT<T>>(skelStates).subspan(0, nFrames),
458 std::span<const MeshStateT<T>>(meshStates).subspan(0, nFrames),
459 jacobian.block(offset, 0, n, nFrames * nFullParameters),
460 residual.middleRows(offset, n),
461 rows);
462
463 MT_CHECK(rows >= 0 && rows <= static_cast<Eigen::Index>(n));
464 offset += rows;
465 }
466
467 // Because we have only one copy of the universal parameters, merge all sub-frame
468 // universal Jacobians into the first block.
469 for (const auto universalIndex : fn->getUniversalParameterIndices()) {
470 for (size_t kSubFrame = 1; kSubFrame < bandwidthCur; ++kSubFrame) {
471 jacobian.col(universalIndex) += jacobian.col(kSubFrame * nFullParameters + universalIndex);
472 }
473 }
474
475 const auto sequenceColumnIndices = detail::buildSequenceColumnIndices(fn, bandwidthCur);
476 return {
477 .jacobian = compactJacobianColumns<T>(
478 jacobian.topRows(offset),
479 std::span<const Eigen::Index>(sequenceColumnIndices.data(), sequenceColumnIndices.size()),
480 fn->getUniversalParameterIndices()),
481 .residual = std::move(residual),
482 .error = errorCur,
483 .nFunctions = nSelectedFunctions,
484 .usedRows = offset,
485 .nBandColumns = static_cast<Eigen::Index>(sequenceColumnIndices.size()),
486 .nFrameColumns = bandwidthCur};
487}
488
489template <typename T, typename NormalEquationScalar>
490struct AccumulationResult {
491 std::unique_ptr<NormalEquationBlock<NormalEquationScalar>> normalEquations;
492 double error = 0.0;
493 size_t nFunctions = 0;
494};
495
496template <typename T, typename NormalEquationScalar>
497AccumulationResult<T, NormalEquationScalar> processChunk(
499 size_t chunkStart,
500 size_t chunkEnd,
501 size_t bandwidthFrames,
502 size_t targetRowsPerJtJChunk) {
503 const Eigen::Index perFrameParams = fn->getPerFrameParameterIndices().size();
504 const Eigen::Index storageBlockSize = std::max<Eigen::Index>(1, perFrameParams);
505 const Eigen::Index nCommon = fn->getUniversalParameterIndices().size();
506 const Eigen::Index nBand = (chunkEnd - chunkStart) * perFrameParams;
507 const Eigen::Index bandwidth = bandwidthFrames * perFrameParams;
508 auto block = std::make_unique<NormalEquationBlock<NormalEquationScalar>>(
509 chunkStart * perFrameParams,
510 nBand,
511 nCommon,
512 bandwidth,
513 NormalEquationScalar(0),
514 storageBlockSize);
515
516 double error = 0.0;
517 size_t nFunctions = 0;
518
519 SkeletonStateT<T> skelState;
520 MeshStateT<T> meshState;
521 for (size_t iFrame = chunkStart; iFrame < chunkEnd; ++iFrame) {
522 auto jacRes = computePerFrameJacobian(fn, iFrame, skelState, meshState);
523 error += jacRes.error;
524 nFunctions += jacRes.nFunctions;
525 if (jacRes.usedRows > 0) {
526 block->add(
527 iFrame * perFrameParams,
528 jacRes.jacobian,
529 jacRes.nBandColumns,
530 jacRes.residual.topRows(jacRes.usedRows),
531 targetRowsPerJtJChunk);
532 }
533 }
534
535 if (!fn->getSequenceErrorFunctions().empty()) {
536 for (size_t iFrame = chunkStart; iFrame < chunkEnd; ++iFrame) {
537 auto jacRes = computeSequenceJacobian(
538 fn, iFrame, bandwidthFrames, chunkEnd, SequenceJacobianSelection::InternalToChunk);
539 error += jacRes.error;
540 nFunctions += jacRes.nFunctions;
541 if (jacRes.usedRows > 0) {
542 block->add(
543 iFrame * perFrameParams,
544 jacRes.jacobian,
545 jacRes.nBandColumns,
546 jacRes.residual.topRows(jacRes.usedRows),
547 targetRowsPerJtJChunk);
548 }
549 }
550 }
551
552 return {.normalEquations = std::move(block), .error = error, .nFunctions = nFunctions};
553}
554
555template <typename T, typename NormalEquationScalar>
556AccumulationResult<T, NormalEquationScalar> processBoundarySequenceFrame(
558 size_t iFrame,
559 size_t bandwidthFrames,
560 size_t chunkEnd,
561 size_t targetRowsPerJtJChunk) {
562 const Eigen::Index perFrameParams = fn->getPerFrameParameterIndices().size();
563 const Eigen::Index storageBlockSize = std::max<Eigen::Index>(1, perFrameParams);
564 const Eigen::Index nCommon = fn->getUniversalParameterIndices().size();
565
566 auto jacRes = computeSequenceJacobian(
567 fn, iFrame, bandwidthFrames, chunkEnd, SequenceJacobianSelection::CrossesChunk);
568 auto block = std::make_unique<NormalEquationBlock<NormalEquationScalar>>(
569 iFrame * perFrameParams,
570 jacRes.nFrameColumns * perFrameParams,
571 nCommon,
572 bandwidthFrames * perFrameParams,
573 NormalEquationScalar(0),
574 storageBlockSize);
575
576 if (jacRes.usedRows > 0) {
577 block->add(
578 iFrame * perFrameParams,
579 jacRes.jacobian,
580 jacRes.nBandColumns,
581 jacRes.residual.topRows(jacRes.usedRows),
582 targetRowsPerJtJChunk);
583 }
584
585 return {
586 .normalEquations = std::move(block), .error = jacRes.error, .nFunctions = jacRes.nFunctions};
587}
588
589template <typename T>
590Eigen::Matrix<T, Eigen::Dynamic, 1> solveCommonNormalEquationsOnly(
591 const NormalEquationBlock<T>& hessian);
592
593template <typename T>
594Eigen::Matrix<T, Eigen::Dynamic, 1> solveNormalEquationsScalarLdlt(
595 const NormalEquationBlock<T>& hessian) {
596 using FactorScalar = double;
597 using FactorMatrixType = Eigen::Matrix<FactorScalar, Eigen::Dynamic, Eigen::Dynamic>;
598 using FactorVectorType = Eigen::Matrix<FactorScalar, Eigen::Dynamic, 1>;
599
600 const Eigen::Index nBand = hessian.nBand();
601 const Eigen::Index nCommon = hessian.nCommon();
602 const Eigen::Index bandwidth = hessian.bandwidth();
603
604 auto hessianBandEntry = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar {
605 MT_CHECK(iRow <= jCol);
606 MT_CHECK(jCol - iRow < bandwidth);
607 if (hessian.hasBlockBand()) {
608 const Eigen::Index blockSize = hessian.blockSize();
609 MT_CHECK(blockSize > 0);
610 const Eigen::Index iBlock = iRow / blockSize;
611 const Eigen::Index jBlock = jCol / blockSize;
612 if (jBlock - iBlock >= hessian.blockBandwidth()) {
613 return FactorScalar(0);
614 }
615 return hessian.blockBandBlock(jBlock, iBlock)(jCol % blockSize, iRow % blockSize);
616 }
617 return hessian.bandEntry(iRow, jCol);
618 };
619
620 FactorMatrixType lBand = FactorMatrixType::Zero(bandwidth, nBand);
621 FactorVectorType diagonal = FactorVectorType::Zero(nBand);
622 auto lEntry = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar& {
623 MT_CHECK(iRow >= jCol);
624 MT_CHECK(iRow - jCol < bandwidth);
625 return lBand(iRow - jCol, jCol);
626 };
627 auto lEntryConst = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar {
628 MT_CHECK(iRow >= jCol);
629 MT_CHECK(iRow - jCol < bandwidth);
630 return lBand(iRow - jCol, jCol);
631 };
632
633 for (Eigen::Index iCol = 0; iCol < nBand; ++iCol) {
634 FactorScalar diag = hessianBandEntry(iCol, iCol);
635 const Eigen::Index kStart = std::max<Eigen::Index>(0, iCol - bandwidth + 1);
636 for (Eigen::Index k = kStart; k < iCol; ++k) {
637 const FactorScalar lik = lEntryConst(iCol, k);
638 diag -= lik * lik * diagonal(k);
639 }
640
641 if (std::abs(diag) <= std::numeric_limits<FactorScalar>::epsilon()) {
642 MT_THROW("Banded LDLT factorization failed at column {}", iCol);
643 }
644 diagonal(iCol) = diag;
645 lEntry(iCol, iCol) = FactorScalar(1);
646
647 const Eigen::Index jEnd = std::min(nBand, iCol + bandwidth);
648 for (Eigen::Index jRow = iCol + 1; jRow < jEnd; ++jRow) {
649 FactorScalar value = hessianBandEntry(iCol, jRow);
650 const auto kStartCur =
651 std::max<Eigen::Index>({0, iCol - bandwidth + 1, jRow - bandwidth + 1});
652 for (Eigen::Index k = kStartCur; k < iCol; ++k) {
653 value -= lEntryConst(jRow, k) * lEntryConst(iCol, k) * diagonal(k);
654 }
655 lEntry(jRow, iCol) = value / diag;
656 }
657 }
658
659 FactorMatrixType e = FactorMatrixType::Zero(nBand, nCommon);
660 FactorVectorType zBand = hessian.rhs().head(nBand).template cast<FactorScalar>();
661
662 for (Eigen::Index iRow = 0; iRow < nBand; ++iRow) {
663 if (nCommon > 0) {
664 e.row(iRow).noalias() = hessian.common().row(iRow).template cast<FactorScalar>();
665 }
666 const Eigen::Index kStart = std::max<Eigen::Index>(0, iRow - bandwidth + 1);
667 for (Eigen::Index k = kStart; k < iRow; ++k) {
668 if (nCommon > 0) {
669 e.row(iRow).noalias() -= lEntryConst(iRow, k) * e.row(k);
670 }
671 zBand(iRow) -= lEntryConst(iRow, k) * zBand(k);
672 }
673 }
674
675 FactorVectorType result = FactorVectorType::Zero(nBand + nCommon);
676 if (nCommon > 0) {
677 FactorMatrixType dInvE = e;
678 FactorVectorType dInvZ = zBand;
679 for (Eigen::Index iRow = 0; iRow < nBand; ++iRow) {
680 dInvE.row(iRow) /= diagonal(iRow);
681 dInvZ(iRow) /= diagonal(iRow);
682 }
683
684 FactorMatrixType schur = hessian.common().bottomRows(nCommon).template cast<FactorScalar>();
685 schur.noalias() -= e.transpose() * dInvE;
686
687 Eigen::LDLT<FactorMatrixType> ldlt(schur);
688 if (ldlt.info() != Eigen::Success) {
689 MT_THROW("Universal LDLT factorization failed");
690 }
691 result.tail(nCommon) = ldlt.solve(
692 hessian.rhs().tail(nCommon).template cast<FactorScalar>() - e.transpose() * dInvZ);
693 }
694
695 FactorVectorType bandRhs = zBand;
696 if (nCommon > 0) {
697 bandRhs.noalias() -= e * result.tail(nCommon);
698 }
699 bandRhs.array() /= diagonal.array();
700
701 for (Eigen::Index iRow = nBand - 1; iRow >= 0; --iRow) {
702 auto dotProd = FactorScalar(0);
703 const Eigen::Index jEnd = std::min(nBand, iRow + bandwidth);
704 for (Eigen::Index jRow = iRow + 1; jRow < jEnd; ++jRow) {
705 dotProd += lEntryConst(jRow, iRow) * result(jRow);
706 }
707 result(iRow) = bandRhs(iRow) - dotProd;
708 }
709
710 if (nBand == 0 && nCommon > 0) {
711 result.tail(nCommon) = solveCommonNormalEquationsOnly(hessian).template cast<FactorScalar>();
712 }
713
714 return result.template cast<T>();
715}
716
717template <typename T>
718Eigen::Matrix<T, Eigen::Dynamic, 1> solveCommonNormalEquationsOnly(
719 const NormalEquationBlock<T>& hessian) {
720 using FactorScalar = double;
721 using FactorMatrixType = Eigen::Matrix<FactorScalar, Eigen::Dynamic, Eigen::Dynamic>;
722
723 const Eigen::Index nCommon = hessian.nCommon();
724 FactorMatrixType common = hessian.common().bottomRows(nCommon).template cast<FactorScalar>();
725 Eigen::LDLT<FactorMatrixType> ldlt(common);
726 MT_THROW_IF(ldlt.info() != Eigen::Success, "Universal LDLT factorization failed");
727 return ldlt.solve(hessian.rhs().tail(nCommon).template cast<FactorScalar>()).template cast<T>();
728}
729
730using BlockFactorScalar = double;
731using BlockFactorMatrixType = Eigen::Matrix<BlockFactorScalar, Eigen::Dynamic, Eigen::Dynamic>;
732using BlockFactorVectorType = Eigen::Matrix<BlockFactorScalar, Eigen::Dynamic, 1>;
733using BlockFactorRefType = Eigen::Ref<BlockFactorMatrixType>;
734using BlockDiagonalLdlt = Eigen::LDLT<BlockFactorRefType>;
735
736struct BlockLdltFactors {
737 Eigen::Index blockSize = 0;
738 Eigen::Index nBlocks = 0;
739 Eigen::Index bandwidthBlocks = 0;
740 BlockFactorMatrixType lowerFactors;
741 // The block-tridiagonal fast path never needs the unfactored diagonal blocks after their
742 // LDLT decompositions have been computed. Wider bands use them when updating later blocks.
743 BlockFactorMatrixType diagonalFactors;
744 std::deque<BlockDiagonalLdlt> diagonalLdltFactors;
745
746 auto lowerFactor(Eigen::Index iBlock, Eigen::Index jBlock) {
747 MT_CHECK(iBlock >= jBlock);
748 const Eigen::Index offset = iBlock - jBlock;
749 MT_CHECK(offset < bandwidthBlocks);
750 return lowerFactors.block(iBlock * blockSize, offset * blockSize, blockSize, blockSize);
751 }
752
753 [[nodiscard]] auto lowerFactor(Eigen::Index iBlock, Eigen::Index jBlock) const {
754 MT_CHECK(iBlock >= jBlock);
755 const Eigen::Index offset = iBlock - jBlock;
756 MT_CHECK(offset < bandwidthBlocks);
757 return lowerFactors.block(iBlock * blockSize, offset * blockSize, blockSize, blockSize);
758 }
759
760 auto diagonalFactor(Eigen::Index iBlock) {
761 return diagonalFactors.block(iBlock * blockSize, 0, blockSize, blockSize);
762 }
763};
764
765template <typename T>
766std::unique_ptr<BlockLdltFactors> factorBlockNormalEquations(
767 NormalEquationBlock<T>& hessian,
768 Eigen::Index blockSize) {
769 const Eigen::Index nBand = hessian.nBand();
770 const Eigen::Index nBlocks = nBand / blockSize;
771 const Eigen::Index bandwidthBlocks = hessian.blockBandwidth();
772
773 // The normal-equation band and the lower factor have the same packed layout. Consume the
774 // former so both full matrices are not resident throughout factorization.
775 BlockFactorMatrixType lowerFactors;
776 if constexpr (std::is_same_v<T, BlockFactorScalar>) {
777 lowerFactors = hessian.takeBlockBand();
778 } else {
779 const auto packedBand = hessian.takeBlockBand();
780 lowerFactors = packedBand.template cast<BlockFactorScalar>();
781 }
782
783 auto factors = std::make_unique<BlockLdltFactors>();
784 factors->blockSize = blockSize;
785 factors->nBlocks = nBlocks;
786 factors->bandwidthBlocks = bandwidthBlocks;
787 factors->lowerFactors = std::move(lowerFactors);
788 factors->diagonalFactors =
789 bandwidthBlocks > 2 ? BlockFactorMatrixType::Zero(nBand, blockSize) : BlockFactorMatrixType();
790
791 BlockFactorMatrixType previousDiagonalUpdate;
792 if (bandwidthBlocks == 2) {
793 previousDiagonalUpdate = BlockFactorMatrixType::Zero(blockSize, blockSize);
794 }
795
796 for (Eigen::Index iBlock = 0; iBlock < nBlocks; ++iBlock) {
797 BlockFactorMatrixType diagonal = factors->lowerFactor(iBlock, iBlock);
798 const Eigen::Index kStart = std::max<Eigen::Index>(0, iBlock - bandwidthBlocks + 1);
799 if (bandwidthBlocks == 2 && iBlock > 0) {
800 // For block-tridiagonal systems, L_ik * D_k * L_ik^T is equivalent to
801 // L_ik * A_ik^T. Carry that update forward because A_ik shares storage with L_ik.
802 diagonal -= previousDiagonalUpdate;
803 } else {
804 for (Eigen::Index kBlock = kStart; kBlock < iBlock; ++kBlock) {
805 const auto& lik = factors->lowerFactor(iBlock, kBlock);
806 diagonal.noalias() -= lik * factors->diagonalFactor(kBlock) * lik.transpose();
807 }
808 }
809
810 if (bandwidthBlocks > 2) {
811 factors->diagonalFactor(iBlock) = diagonal;
812 }
813 auto diagonalBlock = factors->lowerFactor(iBlock, iBlock);
814 diagonalBlock = diagonal;
815 factors->diagonalLdltFactors.emplace_back(diagonalBlock);
816 const auto& diagonalLdlt = factors->diagonalLdltFactors.back();
817 if (diagonalLdlt.info() != Eigen::Success) {
818 MT_THROW("Block banded LDLT factorization failed at block {}", iBlock);
819 }
820
821 const Eigen::Index jEnd = std::min(nBlocks, iBlock + bandwidthBlocks);
822 for (Eigen::Index jBlock = iBlock + 1; jBlock < jEnd; ++jBlock) {
823 BlockFactorMatrixType value = factors->lowerFactor(jBlock, iBlock);
824 const auto kStartCur = std::max<Eigen::Index>({0, jBlock - bandwidthBlocks + 1, kStart});
825 for (Eigen::Index kBlock = kStartCur; kBlock < iBlock; ++kBlock) {
826 value.noalias() -= factors->lowerFactor(jBlock, kBlock) * factors->diagonalFactor(kBlock) *
827 factors->lowerFactor(iBlock, kBlock).transpose();
828 }
829
830 const BlockFactorMatrixType lowerFactor =
831 factors->diagonalLdltFactors.at(static_cast<size_t>(iBlock))
832 .solve(value.transpose())
833 .transpose();
834 if (bandwidthBlocks == 2) {
835 previousDiagonalUpdate.noalias() = lowerFactor * value.transpose();
836 }
837 factors->lowerFactor(jBlock, iBlock) = lowerFactor;
838 }
839 }
840
841 return factors;
842}
843
844void applyBlockForwardSubstitution(
845 const BlockLdltFactors& factors,
846 BlockFactorVectorType& zBand,
847 BlockFactorMatrixType& e) {
848 for (Eigen::Index iBlock = 0; iBlock < factors.nBlocks; ++iBlock) {
849 const Eigen::Index iOffset = iBlock * factors.blockSize;
850 const Eigen::Index kStart = std::max<Eigen::Index>(0, iBlock - factors.bandwidthBlocks + 1);
851 for (Eigen::Index kBlock = kStart; kBlock < iBlock; ++kBlock) {
852 const Eigen::Index kOffset = kBlock * factors.blockSize;
853 zBand.segment(iOffset, factors.blockSize).noalias() -=
854 factors.lowerFactor(iBlock, kBlock) * zBand.segment(kOffset, factors.blockSize);
855 if (e.cols() > 0) {
856 e.middleRows(iOffset, factors.blockSize).noalias() -=
857 factors.lowerFactor(iBlock, kBlock) * e.middleRows(kOffset, factors.blockSize);
858 }
859 }
860 }
861}
862
863void applyBlockDiagonalInverse(
864 const BlockLdltFactors& factors,
865 BlockFactorVectorType& zBand,
866 BlockFactorMatrixType& e) {
867 for (Eigen::Index iBlock = 0; iBlock < factors.nBlocks; ++iBlock) {
868 const Eigen::Index iOffset = iBlock * factors.blockSize;
869 zBand.segment(iOffset, factors.blockSize) =
870 factors.diagonalLdltFactors.at(static_cast<size_t>(iBlock))
871 .solve(zBand.segment(iOffset, factors.blockSize));
872 if (e.cols() > 0) {
873 e.middleRows(iOffset, factors.blockSize) =
874 factors.diagonalLdltFactors.at(static_cast<size_t>(iBlock))
875 .solve(e.middleRows(iOffset, factors.blockSize));
876 }
877 }
878}
879
880template <typename T>
881BlockFactorVectorType solveCommonBlock(
882 const NormalEquationBlock<T>& hessian,
883 const BlockFactorMatrixType& e,
884 const BlockFactorMatrixType& dInvE,
885 const BlockFactorVectorType& dInvZ) {
886 const Eigen::Index nCommon = hessian.nCommon();
887 BlockFactorMatrixType schur =
888 hessian.common().bottomRows(nCommon).template cast<BlockFactorScalar>();
889 schur.noalias() -= e.transpose() * dInvE;
890
891 Eigen::LDLT<BlockFactorMatrixType> ldlt(schur);
892 if (ldlt.info() != Eigen::Success) {
893 MT_THROW("Universal LDLT factorization failed");
894 }
895 return ldlt.solve(
896 hessian.rhs().tail(nCommon).template cast<BlockFactorScalar>() - e.transpose() * dInvZ);
897}
898
899BlockFactorVectorType solveBlockBandVariables(
900 const BlockLdltFactors& factors,
901 BlockFactorVectorType bandRhs) {
902 for (Eigen::Index iBlock = 0; iBlock < factors.nBlocks; ++iBlock) {
903 const Eigen::Index iOffset = iBlock * factors.blockSize;
904 bandRhs.segment(iOffset, factors.blockSize) =
905 factors.diagonalLdltFactors.at(static_cast<size_t>(iBlock))
906 .solve(bandRhs.segment(iOffset, factors.blockSize));
907 }
908
909 BlockFactorVectorType result = BlockFactorVectorType::Zero(factors.nBlocks * factors.blockSize);
910 for (Eigen::Index iBlock = factors.nBlocks - 1; iBlock >= 0; --iBlock) {
911 const Eigen::Index iOffset = iBlock * factors.blockSize;
912 const Eigen::Index jEnd = std::min(factors.nBlocks, iBlock + factors.bandwidthBlocks);
913 for (Eigen::Index jBlock = iBlock + 1; jBlock < jEnd; ++jBlock) {
914 const Eigen::Index jOffset = jBlock * factors.blockSize;
915 bandRhs.segment(iOffset, factors.blockSize).noalias() -=
916 factors.lowerFactor(jBlock, iBlock).transpose() *
917 result.segment(jOffset, factors.blockSize);
918 }
919
920 result.segment(iOffset, factors.blockSize) = bandRhs.segment(iOffset, factors.blockSize);
921 }
922 return result;
923}
924
925template <typename T>
926Eigen::Matrix<T, Eigen::Dynamic, 1> solveNormalEquationsBlock(
927 NormalEquationBlock<T>& hessian,
928 Eigen::Index blockSize) {
929 const Eigen::Index nBand = hessian.nBand();
930 const Eigen::Index nCommon = hessian.nCommon();
931 MT_CHECK(blockSize > 0);
932 MT_CHECK(nBand % blockSize == 0);
933
934 const auto factors = factorBlockNormalEquations(hessian, blockSize);
935
936 BlockFactorVectorType zBand = hessian.rhs().head(nBand).template cast<BlockFactorScalar>();
937 BlockFactorMatrixType e = BlockFactorMatrixType::Zero(nBand, nCommon);
938 if (nCommon > 0) {
939 e = hessian.common().topRows(nBand).template cast<BlockFactorScalar>();
940 }
941
942 applyBlockForwardSubstitution(*factors, zBand, e);
943
944 BlockFactorVectorType result = BlockFactorVectorType::Zero(nBand + nCommon);
945 if (nCommon > 0) {
946 BlockFactorMatrixType dInvE = e;
947 BlockFactorVectorType dInvZ = zBand;
948 applyBlockDiagonalInverse(*factors, dInvZ, dInvE);
949 result.tail(nCommon) = solveCommonBlock(hessian, e, dInvE, dInvZ);
950 }
951
952 BlockFactorVectorType bandRhs = zBand;
953 if (nCommon > 0) {
954 bandRhs.noalias() -= e * result.tail(nCommon);
955 }
956 result.head(nBand) = solveBlockBandVariables(*factors, bandRhs);
957
958 return result.template cast<T>();
959}
960
961template <typename T>
962Eigen::Matrix<T, Eigen::Dynamic, 1>
963solveNormalEquations(NormalEquationBlock<T>& hessian, Eigen::Index blockSize, bool useBlockLdlt) {
964 if (!useBlockLdlt || hessian.nBand() == 0 || blockSize <= 1 || hessian.nBand() % blockSize != 0 ||
965 hessian.bandwidth() % blockSize != 0 || !hessian.hasBlockBand()) {
966 return solveNormalEquationsScalarLdlt(hessian);
967 }
968
969 return solveNormalEquationsBlock(hessian, blockSize);
970}
971
972} // namespace
973
974template <typename T>
976 const SolverOptions& options,
978 : SequenceSolverBaseT<T>(options, function) {
980 targetRowsPerJtJChunk_ = SequenceCholeskySolverOptions().targetRowsPerJtJChunk;
982
983 setOptions(options);
984}
985
986template <typename T>
987std::string_view SequenceCholeskySolverT<T>::getName() const {
988 return "SequenceCholeskySolver";
989}
990
991template <typename T>
994
995 if (const auto* derivedOptions = dynamic_cast<const SequenceCholeskySolverOptions*>(&options)) {
996 chunkSize_ = std::max<size_t>(1, derivedOptions->chunkSize);
997 targetRowsPerJtJChunk_ = std::max<size_t>(1, derivedOptions->targetRowsPerJtJChunk);
998 useBlockLdlt_ = derivedOptions->useBlockLdlt;
999 useDoublePrecisionNormalEquations_ = derivedOptions->useDoublePrecisionNormalEquations;
1000 }
1001}
1002
1003template <typename T>
1006
1007 auto* fn = static_cast<SequenceSolverFunctionT<T>*>(this->solverFunction_);
1008
1009 this->bandwidth_ = 1;
1010 for (const auto& frameErrf : fn->getSequenceErrorFunctions()) {
1011 for (const auto& errf : frameErrf) {
1012 this->bandwidth_ = std::max(this->bandwidth_, errf->numFrames());
1013 }
1014 }
1015}
1016
1017template <typename T>
1019 if constexpr (std::is_same_v<T, double>) {
1020 doIterationWithNormalEquationScalar<double>();
1021 } else {
1022 if (useDoublePrecisionNormalEquations_) {
1023 doIterationWithNormalEquationScalar<double>();
1024 } else {
1025 doIterationWithNormalEquationScalar<T>();
1026 }
1027 }
1028}
1029
1030template <typename T>
1031template <typename NormalEquationScalar>
1032void SequenceCholeskySolverT<T>::doIterationWithNormalEquationScalar() {
1034
1035 const auto normalEquationStart = std::chrono::steady_clock::now();
1036
1037 auto* fnPtr = static_cast<SequenceSolverFunctionT<T>*>(this->solverFunction_);
1038 MT_CHECK(fnPtr != nullptr);
1039 auto& fn = *fnPtr;
1040
1041 fn.setFrameParametersFromJoinedParameterVector(this->parameters_);
1042
1043 const Eigen::Index perFrameParams = fn.getPerFrameParameterIndices().size();
1044 const Eigen::Index storageBlockSize = std::max<Eigen::Index>(1, perFrameParams);
1045 const Eigen::Index nBand = fn.getNumFrames() * perFrameParams;
1046 const Eigen::Index nCommon = fn.getUniversalParameterIndices().size();
1047 const Eigen::Index bandwidth = this->bandwidth_ * perFrameParams;
1048 NormalEquationBlock<NormalEquationScalar> globalHessian(
1049 0, nBand, nCommon, bandwidth, NormalEquationScalar(this->regularization_), storageBlockSize);
1050
1051 const size_t chunkSize = std::max<size_t>(1, chunkSize_);
1052 const size_t nChunks = (fn.getNumFrames() + chunkSize - 1) / chunkSize;
1053
1054 std::unique_ptr<ProgressBar> progress;
1055 if (this->progressBar_) {
1056 progress = std::make_unique<ProgressBar>(
1057 "Solving sequence",
1058 fn.numTotalPerFrameErrorFunctions_ + fn.numTotalSequenceErrorFunctions_);
1059 }
1060
1061 this->error_ = 0;
1062 const auto mergeChunkResult = [&](AccumulationResult<T, NormalEquationScalar>& result) {
1063 globalHessian.mergeBlock(*result.normalEquations);
1064 this->error_ += result.error;
1065 if (progress) {
1066 progress->increment(result.nFunctions);
1067 }
1068 result.normalEquations.reset();
1069 };
1070
1071 if (this->multithreaded_) {
1072 const auto workerCount = dispenso::globalThreadPool().numThreads();
1073 const size_t chunksPerBatch =
1074 std::min(nChunks, workerCount > 0 ? static_cast<size_t>(workerCount + 1) : size_t(1));
1075 std::vector<AccumulationResult<T, NormalEquationScalar>> chunkResults(chunksPerBatch);
1076 for (size_t batchStart = 0; batchStart < nChunks; batchStart += chunksPerBatch) {
1077 const size_t batchSize = std::min(chunksPerBatch, nChunks - batchStart);
1078 dispenso::parallel_for(size_t(0), batchSize, [&](size_t iResult) {
1079 const size_t iChunk = batchStart + iResult;
1080 const size_t chunkStart = iChunk * chunkSize;
1081 const size_t chunkEnd = std::min(fn.getNumFrames(), chunkStart + chunkSize);
1082 chunkResults[iResult] = processChunk<T, NormalEquationScalar>(
1083 &fn, chunkStart, chunkEnd, this->bandwidth_, targetRowsPerJtJChunk_);
1084 });
1085 for (size_t iResult = 0; iResult < batchSize; ++iResult) {
1086 mergeChunkResult(chunkResults[iResult]);
1087 }
1088 }
1089 } else {
1090 for (size_t iChunk = 0; iChunk < nChunks; ++iChunk) {
1091 const size_t chunkStart = iChunk * chunkSize;
1092 const size_t chunkEnd = std::min(fn.getNumFrames(), chunkStart + chunkSize);
1093 auto result = processChunk<T, NormalEquationScalar>(
1094 &fn, chunkStart, chunkEnd, this->bandwidth_, targetRowsPerJtJChunk_);
1095 mergeChunkResult(result);
1096 }
1097 }
1098
1099 if (fn.numTotalSequenceErrorFunctions_ != 0) {
1100 for (size_t iChunk = 0; iChunk < nChunks; ++iChunk) {
1101 const size_t chunkStart = iChunk * chunkSize;
1102 const size_t chunkEnd = std::min(fn.getNumFrames(), chunkStart + chunkSize);
1103 size_t boundaryStart = chunkEnd;
1104 if (this->bandwidth_ > 1) {
1105 const size_t boundaryFrames = this->bandwidth_ - 1;
1106 boundaryStart = chunkEnd > boundaryFrames ? std::max(chunkStart, chunkEnd - boundaryFrames)
1107 : chunkStart;
1108 }
1109 for (size_t iFrame = boundaryStart; iFrame < chunkEnd; ++iFrame) {
1110 auto result = processBoundarySequenceFrame<T, NormalEquationScalar>(
1111 &fn, iFrame, this->bandwidth_, chunkEnd, targetRowsPerJtJChunk_);
1112 globalHessian.mergeBlock(*result.normalEquations);
1113 this->error_ += result.error;
1114 if (progress) {
1115 progress->increment(result.nFunctions);
1116 }
1117 }
1118 }
1119 }
1120
1121 const auto normalEquationEnd = std::chrono::steady_clock::now();
1122 lastNormalEquationTimeMs_ =
1123 std::chrono::duration<double, std::milli>(normalEquationEnd - normalEquationStart).count();
1124
1125 const auto linearSolveStart = std::chrono::steady_clock::now();
1126 const Eigen::Matrix<NormalEquationScalar, Eigen::Dynamic, 1> normalEquationSearchDir =
1127 solveNormalEquations(globalHessian, storageBlockSize, useBlockLdlt_);
1128 const Eigen::VectorX<T>& searchDir = normalEquationSearchDir.template cast<T>();
1129 const auto linearSolveEnd = std::chrono::steady_clock::now();
1130 lastLinearSolveTimeMs_ =
1131 std::chrono::duration<double, std::milli>(linearSolveEnd - linearSolveStart).count();
1132
1133 const double errorOrig = this->error_;
1134 if (this->doLineSearch_) {
1135 const double innerProd = -globalHessian.rhs().dot(normalEquationSearchDir);
1136
1137 const float c1 = 1e-4f;
1138 const float tau = 0.5f;
1139 float alpha = 1.0f;
1140
1141 const Eigen::VectorX<T> parametersOrig = this->parameters_;
1142 for (size_t kStep = 0; kStep < 10 && std::fpclassify(alpha) == FP_NORMAL; ++kStep) {
1143 this->parameters_ = parametersOrig;
1144 this->solverFunction_->updateParameters(this->parameters_, alpha * searchDir);
1145
1146 const double errorNew = this->solverFunction_->getError(this->parameters_);
1147 if ((errorOrig - errorNew) >= c1 * alpha * -innerProd) {
1148 break;
1149 }
1150
1151 alpha = alpha * tau;
1152 }
1153 } else {
1154 this->solverFunction_->updateParameters(this->parameters_, searchDir);
1155 }
1156}
1157
1158template class SequenceCholeskySolverT<float>;
1159template class SequenceCholeskySolverT<double>;
1160
1161} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Sequence solver based on banded normal equations and banded factorization.
void initializeSolver() final
Initializes solver state before optimization begins.
SequenceCholeskySolverT(const SolverOptions &options, SequenceSolverFunctionT< T > *function)
void doIteration() final
Performs a single iteration of the optimization algorithm.
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.
SequenceSolverBaseT(const SolverOptions &options, SequenceSolverFunctionT< T > *function)
void setOptions(const SolverOptions &options) override
Updates solver configuration with new options.
SolverFunctionT< T > * solverFunction_
Function to be optimized.
Definition solver.h:106
#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
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.
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
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
Sequence Cholesky solver specific options.
bool useBlockLdlt
Use the block LDLT factorization path when the band layout is block-compatible.
size_t chunkSize
Number of frames processed by one independent accumulation chunk.
size_t targetRowsPerJtJChunk
Target number of Jacobian rows per local J^T J multiplication.
Represents the complete state of a skeleton.
Common options for numerical optimization solvers.
Definition solver.h:19