22#include <dispenso/parallel_for.h>
23#include <dispenso/thread_pool.h>
25#include <Eigen/Cholesky>
42struct JacobianResidual {
43 Eigen::MatrixX<T> jacobian;
44 Eigen::VectorX<T> residual;
46 size_t nFunctions = 0;
47 Eigen::Index usedRows = 0;
48 Eigen::Index nBandColumns = 0;
49 size_t nFrameColumns = 0;
52enum class SequenceJacobianSelection { All, InternalToChunk, CrossesChunk };
55bool useSequenceErrorFunction(
59 SequenceJacobianSelection selection) {
61 case SequenceJacobianSelection::All:
63 case SequenceJacobianSelection::InternalToChunk:
64 return iFrame + errf.numFrames() <= chunkEnd;
65 case SequenceJacobianSelection::CrossesChunk:
66 return iFrame + errf.numFrames() > chunkEnd;
68 MT_THROW(
"Unhandled sequence Jacobian selection");
72class NormalEquationBlock {
74 using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
75 using VectorType = Eigen::Matrix<T, Eigen::Dynamic, 1>;
78 Eigen::Index iColOffset,
81 Eigen::Index bandwidth,
83 Eigen::Index blockSize = 1)
84 : iColOffset_(iColOffset),
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_);
95 band_ = MatrixType::Zero(bandwidth, nBand);
99 for (Eigen::Index iBlock = 0; iBlock < nBand / blockSize_; ++iBlock) {
100 blockBandBlock(iBlock, iBlock).diagonal().array() += regularization;
103 for (Eigen::Index iCol = 0; iCol < nBand; ++iCol) {
104 bandEntry(iCol, iCol) = regularization;
108 common_.bottomRightCorner(nCommon, nCommon).diagonal().setConstant(regularization);
112 [[nodiscard]] Eigen::Index iColOffset()
const {
116 [[nodiscard]] Eigen::Index nBand()
const {
120 [[nodiscard]] Eigen::Index nCommon()
const {
121 return common_.cols();
124 [[nodiscard]] Eigen::Index bandwidth()
const {
128 [[nodiscard]]
bool hasBlockBand()
const {
129 return blockBandwidth_ > 0;
132 [[nodiscard]] Eigen::Index blockSize()
const {
136 [[nodiscard]] Eigen::Index blockBandwidth()
const {
137 return blockBandwidth_;
140 [[nodiscard]]
const MatrixType& band()
const {
144 [[nodiscard]]
const MatrixType& common()
const {
148 [[nodiscard]]
const VectorType& rhs()
const {
152 MatrixType takeBlockBand() {
154 return std::move(blockBand_);
157 auto blockBandBlock(Eigen::Index iBlock, Eigen::Index jBlock) {
160 const Eigen::Index offset = iBlock - jBlock;
162 return blockBand_.block(iBlock * blockSize_, offset * blockSize_, blockSize_, blockSize_);
165 [[nodiscard]]
auto blockBandBlock(Eigen::Index iBlock, Eigen::Index jBlock)
const {
168 const Eigen::Index offset = iBlock - jBlock;
170 return blockBand_.block(iBlock * blockSize_, offset * blockSize_, blockSize_, blockSize_);
173 [[nodiscard]] T bandEntry(Eigen::Index iRowLocal, Eigen::Index jColLocal)
const {
175 MT_CHECK(jColLocal - iRowLocal < bandwidth());
176 return band_(bandwidth() + iRowLocal - jColLocal - 1, jColLocal);
179 [[nodiscard]] T& bandEntry(Eigen::Index iRowLocal, Eigen::Index jColLocal) {
181 MT_CHECK(jColLocal - iRowLocal < bandwidth());
182 return band_(bandwidth() + iRowLocal - jColLocal - 1, jColLocal);
185 template <
typename JacobianDerived,
typename Res
idualDerived>
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());
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_;
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>();
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);
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);
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_) {
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);
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()) {
254 bandEntry(iLocal, jLocal) += localHessian(iBand, jBand);
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());
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_;
272 for (Eigen::Index iCol = 0; iCol < rhs.nBand(); ++iCol) {
273 for (Eigen::Index iRow = std::max<Eigen::Index>(0, iCol - rhs.bandwidth() + 1);
276 bandEntry(localOffset + iRow, localOffset + iCol) += rhs.bandEntry(iRow, iCol);
281 if (rhs.nBand() > 0) {
283 common_.middleRows(localOffset, rhs.nBand()).noalias() += rhs.common().topRows(rhs.nBand());
285 rhs_.segment(localOffset, rhs.nBand()).noalias() += rhs.rhs().head(rhs.nBand());
288 common_.bottomRows(nCommon()).noalias() += rhs.common().bottomRows(rhs.nCommon());
289 rhs_.tail(nCommon()).noalias() += rhs.rhs().tail(rhs.nCommon());
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;
300 MatrixType blockBand_;
313 (*fn->getParameterTransform()).apply(fn->getFrameParameters()[iFrame]),
314 fn->getCharacter().skeleton);
316 meshState.update(fn->getFrameParameters()[iFrame], skelState, fn->getCharacter());
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(
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);
333 for (
const Eigen::Index iCol : commonColumnIndices) {
334 MT_CHECK(iCol >= 0 && iCol < jacobian.cols());
335 result.col(iOut++) = jacobian.col(iCol);
341JacobianResidual<T> computePerFrameJacobian(
346 computeState(fn, iFrame, fn->needsMeshPerFrame(), skelState, meshState);
348 const auto nFullParameters = (*fn->getParameterTransform()).numAllModelParameters();
349 const auto jacobianSize =
351 Eigen::MatrixX<T> jacobian = Eigen::MatrixX<T>::Zero(jacobianSize, nFullParameters);
352 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
354 Eigen::Index offset = 0;
356 for (
const auto& errf : fn->getErrorFunctions()[iFrame]) {
357 if (errf->getWeight() <= 0.0f) {
361 const auto n = errf->getJacobianSize();
364 errorCur += errf->getJacobian(
365 fn->getFrameParameters()[iFrame],
368 jacobian.block(offset, 0, n, nFullParameters),
369 residual.middleRows(offset, n),
372 MT_CHECK(rows >= 0 && rows <=
static_cast<Eigen::Index
>(n));
377 .jacobian = compactJacobianColumns<T>(
378 jacobian.topRows(offset),
379 fn->getPerFrameParameterIndices(),
380 fn->getUniversalParameterIndices()),
381 .residual = std::move(residual),
383 .nFunctions = fn->getErrorFunctions()[iFrame].size(),
385 .nBandColumns =
static_cast<Eigen::Index
>(fn->getPerFrameParameterIndices().size())};
389JacobianResidual<T> computeSequenceJacobian(
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)) {
403 ++nSelectedFunctions;
404 if (errf->getWeight() <= 0) {
407 bandwidthCur = std::max(bandwidthCur, errf->numFrames());
408 jacobianSizeRaw += errf->getJacobianSize();
410 MT_CHECK(bandwidthCur <= maxBandwidthCur);
412 if (bandwidthCur == 0) {
414 .jacobian = Eigen::MatrixX<T>::Zero(
415 0,
static_cast<Eigen::Index
>(fn->getUniversalParameterIndices().size())),
416 .residual = Eigen::VectorX<T>::Zero(0),
418 .nFunctions = nSelectedFunctions,
424 std::vector<SkeletonStateT<T>> skelStates(bandwidthCur);
425 std::vector<MeshStateT<T>> meshStates(bandwidthCur);
426 for (
size_t kSubFrame = 0; kSubFrame < bandwidthCur; ++kSubFrame) {
430 fn->needsMeshSequence(),
431 skelStates[kSubFrame],
432 meshStates[kSubFrame]);
435 const auto nFullParameters = (*fn->getParameterTransform()).numAllModelParameters();
437 Eigen::MatrixX<T> jacobian =
438 Eigen::MatrixX<T>::Zero(jacobianSize, bandwidthCur * nFullParameters);
439 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
441 Eigen::Index offset = 0;
443 for (
const auto& errf : fn->getSequenceErrorFunctions()[iFrame]) {
444 if (!useSequenceErrorFunction(*errf, iFrame, chunkEnd, selection)) {
447 if (errf->getWeight() <= 0.0f) {
451 const auto nFrames = errf->numFrames();
453 const size_t n = errf->getJacobianSize();
455 errorCur += errf->getJacobian(
456 std::span(fn->getFrameParameters()).subspan(iFrame, nFrames),
458 std::span<
const MeshStateT<T>>(meshStates).subspan(0, nFrames),
459 jacobian.block(offset, 0, n, nFrames * nFullParameters),
460 residual.middleRows(offset, n),
463 MT_CHECK(rows >= 0 && rows <=
static_cast<Eigen::Index
>(n));
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);
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),
483 .nFunctions = nSelectedFunctions,
485 .nBandColumns =
static_cast<Eigen::Index
>(sequenceColumnIndices.size()),
486 .nFrameColumns = bandwidthCur};
489template <
typename T,
typename NormalEquationScalar>
490struct AccumulationResult {
491 std::unique_ptr<NormalEquationBlock<NormalEquationScalar>> normalEquations;
493 size_t nFunctions = 0;
496template <
typename T,
typename NormalEquationScalar>
497AccumulationResult<T, NormalEquationScalar> processChunk(
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,
513 NormalEquationScalar(0),
517 size_t nFunctions = 0;
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) {
527 iFrame * perFrameParams,
530 jacRes.residual.topRows(jacRes.usedRows),
531 targetRowsPerJtJChunk);
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) {
543 iFrame * perFrameParams,
546 jacRes.residual.topRows(jacRes.usedRows),
547 targetRowsPerJtJChunk);
552 return {.normalEquations = std::move(block), .error = error, .nFunctions = nFunctions};
555template <
typename T,
typename NormalEquationScalar>
556AccumulationResult<T, NormalEquationScalar> processBoundarySequenceFrame(
559 size_t bandwidthFrames,
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();
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,
572 bandwidthFrames * perFrameParams,
573 NormalEquationScalar(0),
576 if (jacRes.usedRows > 0) {
578 iFrame * perFrameParams,
581 jacRes.residual.topRows(jacRes.usedRows),
582 targetRowsPerJtJChunk);
586 .normalEquations = std::move(block), .error = jacRes.error, .nFunctions = jacRes.nFunctions};
590Eigen::Matrix<T, Eigen::Dynamic, 1> solveCommonNormalEquationsOnly(
591 const NormalEquationBlock<T>& hessian);
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>;
600 const Eigen::Index nBand = hessian.nBand();
601 const Eigen::Index nCommon = hessian.nCommon();
602 const Eigen::Index bandwidth = hessian.bandwidth();
604 auto hessianBandEntry = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar {
607 if (hessian.hasBlockBand()) {
608 const Eigen::Index blockSize = hessian.blockSize();
610 const Eigen::Index iBlock = iRow / blockSize;
611 const Eigen::Index jBlock = jCol / blockSize;
612 if (jBlock - iBlock >= hessian.blockBandwidth()) {
613 return FactorScalar(0);
615 return hessian.blockBandBlock(jBlock, iBlock)(jCol % blockSize, iRow % blockSize);
617 return hessian.bandEntry(iRow, jCol);
620 FactorMatrixType lBand = FactorMatrixType::Zero(bandwidth, nBand);
621 FactorVectorType diagonal = FactorVectorType::Zero(nBand);
622 auto lEntry = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar& {
625 return lBand(iRow - jCol, jCol);
627 auto lEntryConst = [&](Eigen::Index iRow, Eigen::Index jCol) -> FactorScalar {
630 return lBand(iRow - jCol, jCol);
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);
641 if (std::abs(diag) <= std::numeric_limits<FactorScalar>::epsilon()) {
642 MT_THROW(
"Banded LDLT factorization failed at column {}", iCol);
644 diagonal(iCol) = diag;
645 lEntry(iCol, iCol) = FactorScalar(1);
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);
655 lEntry(jRow, iCol) = value / diag;
659 FactorMatrixType e = FactorMatrixType::Zero(nBand, nCommon);
662 for (Eigen::Index iRow = 0; iRow < nBand; ++iRow) {
666 const Eigen::Index kStart = std::max<Eigen::Index>(0, iRow - bandwidth + 1);
667 for (Eigen::Index k = kStart; k < iRow; ++k) {
669 e.row(iRow).noalias() -= lEntryConst(iRow, k) * e.row(k);
671 zBand(iRow) -= lEntryConst(iRow, k) * zBand(k);
675 FactorVectorType result = FactorVectorType::Zero(nBand + nCommon);
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);
684 FactorMatrixType schur = hessian.common().bottomRows(nCommon).template
cast<FactorScalar>();
685 schur.noalias() -= e.transpose() * dInvE;
687 Eigen::LDLT<FactorMatrixType> ldlt(schur);
688 if (ldlt.info() != Eigen::Success) {
689 MT_THROW(
"Universal LDLT factorization failed");
691 result.tail(nCommon) = ldlt.solve(
695 FactorVectorType bandRhs = zBand;
697 bandRhs.noalias() -= e * result.tail(nCommon);
699 bandRhs.array() /= diagonal.array();
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);
707 result(iRow) = bandRhs(iRow) - dotProd;
710 if (nBand == 0 && nCommon > 0) {
711 result.tail(nCommon) = solveCommonNormalEquationsOnly(hessian).template
cast<FactorScalar>();
714 return result.template
cast<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>;
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");
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>;
736struct BlockLdltFactors {
737 Eigen::Index blockSize = 0;
738 Eigen::Index nBlocks = 0;
739 Eigen::Index bandwidthBlocks = 0;
740 BlockFactorMatrixType lowerFactors;
743 BlockFactorMatrixType diagonalFactors;
744 std::deque<BlockDiagonalLdlt> diagonalLdltFactors;
746 auto lowerFactor(Eigen::Index iBlock, Eigen::Index jBlock) {
748 const Eigen::Index offset = iBlock - jBlock;
750 return lowerFactors.block(iBlock * blockSize, offset * blockSize, blockSize, blockSize);
753 [[nodiscard]]
auto lowerFactor(Eigen::Index iBlock, Eigen::Index jBlock)
const {
755 const Eigen::Index offset = iBlock - jBlock;
757 return lowerFactors.block(iBlock * blockSize, offset * blockSize, blockSize, blockSize);
760 auto diagonalFactor(Eigen::Index iBlock) {
761 return diagonalFactors.block(iBlock * blockSize, 0, blockSize, blockSize);
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();
775 BlockFactorMatrixType lowerFactors;
776 if constexpr (std::is_same_v<T, BlockFactorScalar>) {
777 lowerFactors = hessian.takeBlockBand();
779 const auto packedBand = hessian.takeBlockBand();
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();
791 BlockFactorMatrixType previousDiagonalUpdate;
792 if (bandwidthBlocks == 2) {
793 previousDiagonalUpdate = BlockFactorMatrixType::Zero(blockSize, blockSize);
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) {
802 diagonal -= previousDiagonalUpdate;
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();
810 if (bandwidthBlocks > 2) {
811 factors->diagonalFactor(iBlock) = diagonal;
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);
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();
830 const BlockFactorMatrixType lowerFactor =
831 factors->diagonalLdltFactors.at(
static_cast<size_t>(iBlock))
832 .solve(value.transpose())
834 if (bandwidthBlocks == 2) {
835 previousDiagonalUpdate.noalias() = lowerFactor * value.transpose();
837 factors->lowerFactor(jBlock, iBlock) = lowerFactor;
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);
856 e.middleRows(iOffset, factors.blockSize).noalias() -=
857 factors.lowerFactor(iBlock, kBlock) * e.middleRows(kOffset, factors.blockSize);
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));
873 e.middleRows(iOffset, factors.blockSize) =
874 factors.diagonalLdltFactors.at(
static_cast<size_t>(iBlock))
875 .solve(e.middleRows(iOffset, factors.blockSize));
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 =
889 schur.noalias() -= e.transpose() * dInvE;
891 Eigen::LDLT<BlockFactorMatrixType> ldlt(schur);
892 if (ldlt.info() != Eigen::Success) {
893 MT_THROW(
"Universal LDLT factorization failed");
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));
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);
920 result.segment(iOffset, factors.blockSize) = bandRhs.segment(iOffset, factors.blockSize);
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();
934 const auto factors = factorBlockNormalEquations(hessian, blockSize);
937 BlockFactorMatrixType e = BlockFactorMatrixType::Zero(nBand, nCommon);
942 applyBlockForwardSubstitution(*factors, zBand, e);
944 BlockFactorVectorType result = BlockFactorVectorType::Zero(nBand + nCommon);
946 BlockFactorMatrixType dInvE = e;
947 BlockFactorVectorType dInvZ = zBand;
948 applyBlockDiagonalInverse(*factors, dInvZ, dInvE);
949 result.tail(nCommon) = solveCommonBlock(hessian, e, dInvE, dInvZ);
952 BlockFactorVectorType bandRhs = zBand;
954 bandRhs.noalias() -= e * result.tail(nCommon);
956 result.head(nBand) = solveBlockBandVariables(*factors, bandRhs);
958 return result.template
cast<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);
969 return solveNormalEquationsBlock(hessian, blockSize);
988 return "SequenceCholeskySolver";
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;
1003template <
typename T>
1010 for (
const auto& frameErrf : fn->getSequenceErrorFunctions()) {
1011 for (
const auto& errf : frameErrf) {
1012 this->bandwidth_ = std::max(this->bandwidth_, errf->numFrames());
1017template <
typename T>
1019 if constexpr (std::is_same_v<T, double>) {
1020 doIterationWithNormalEquationScalar<double>();
1022 if (useDoublePrecisionNormalEquations_) {
1023 doIterationWithNormalEquationScalar<double>();
1025 doIterationWithNormalEquationScalar<T>();
1030template <
typename T>
1031template <
typename NormalEquationScalar>
1032void SequenceCholeskySolverT<T>::doIterationWithNormalEquationScalar() {
1035 const auto normalEquationStart = std::chrono::steady_clock::now();
1041 fn.setFrameParametersFromJoinedParameterVector(this->parameters_);
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);
1051 const size_t chunkSize = std::max<size_t>(1, chunkSize_);
1052 const size_t nChunks = (fn.getNumFrames() + chunkSize - 1) / chunkSize;
1054 std::unique_ptr<ProgressBar> progress;
1055 if (this->progressBar_) {
1056 progress = std::make_unique<ProgressBar>(
1058 fn.numTotalPerFrameErrorFunctions_ + fn.numTotalSequenceErrorFunctions_);
1062 const auto mergeChunkResult = [&](AccumulationResult<T, NormalEquationScalar>& result) {
1063 globalHessian.mergeBlock(*result.normalEquations);
1064 this->error_ += result.error;
1066 progress->increment(result.nFunctions);
1068 result.normalEquations.reset();
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_);
1085 for (
size_t iResult = 0; iResult < batchSize; ++iResult) {
1086 mergeChunkResult(chunkResults[iResult]);
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);
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)
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;
1115 progress->increment(result.nFunctions);
1121 const auto normalEquationEnd = std::chrono::steady_clock::now();
1122 lastNormalEquationTimeMs_ =
1123 std::chrono::duration<double, std::milli>(normalEquationEnd - normalEquationStart).count();
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();
1133 const double errorOrig = this->error_;
1134 if (this->doLineSearch_) {
1135 const double innerProd = -globalHessian.rhs().dot(normalEquationSearchDir);
1137 const float c1 = 1e-4f;
1138 const float tau = 0.5f;
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);
1146 const double errorNew = this->solverFunction_->getError(this->parameters_);
1147 if ((errorOrig - errorNew) >= c1 * alpha * -innerProd) {
1151 alpha = alpha * tau;
1154 this->solverFunction_->updateParameters(this->parameters_, searchDir);
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
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.
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
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.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Represents the complete state of a model's mesh.
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.