23#include <dispenso/parallel_for.h>
39 return "SequenceSolver";
55 for (
const auto& frameErrf : fn->sequenceErrorFunctions_) {
56 for (
const auto& errf : frameErrf) {
64typename SequenceSolverT<T>::JacobianResidual SequenceSolverT<T>::computePerFrameJacobian(
69 const auto& frameParameters = fn->frameParameters_[iFrame];
73 skelState.
set(fn->parameterTransform_.apply(frameParameters), character.skeleton);
76 meshState.
update(frameParameters, skelState, character);
79 const auto nFullParameters = fn->parameterTransform_.numAllModelParameters();
80 const auto jacobianSize =
82 Eigen::MatrixX<T> jacobian = Eigen::MatrixX<T>::Zero(jacobianSize, nFullParameters);
83 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
85 Eigen::Index offset = 0;
87 for (
const auto& errf : fn->perFrameErrorFunctions_[iFrame]) {
88 if (errf->getWeight() <= 0.0f) {
92 const auto n = errf->getJacobianSize();
95 errorCur += errf->getJacobian(
99 jacobian.block(offset, 0, n, nFullParameters),
100 residual.middleRows(offset, n),
103 MT_CHECK(rows >= 0 && rows <=
static_cast<Eigen::Index
>(n));
109 .frameIndex = iFrame,
110 .jacobian = std::move(jacobian),
111 .residual = std::move(residual),
113 .nFunctions = fn->perFrameErrorFunctions_[iFrame].size(),
118typename SequenceSolverT<T>::JacobianResidual SequenceSolverT<T>::computeSequenceJacobian(
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);
128 const auto nFullParameters = fn->parameterTransform_.numAllModelParameters();
129 const size_t jacobianSize =
131 Eigen::MatrixX<T> jacobian =
132 Eigen::MatrixX<T>::Zero(jacobianSize, bandwidth_cur * nFullParameters);
133 Eigen::VectorX<T> residual = Eigen::VectorX<T>::Zero(jacobianSize);
135 Eigen::Index offset = 0;
137 for (
const auto& errf : fn->sequenceErrorFunctions_[iFrame]) {
138 if (errf->getWeight() <= 0.0f) {
142 const auto nFrames = errf->numFrames();
144 const size_t n = errf->getJacobianSize();
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),
154 MT_CHECK(rows >= 0 && rows <=
static_cast<Eigen::Index
>(n));
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]);
168 .frameIndex = iFrame,
169 .jacobian = std::move(jacobian),
170 .residual = std::move(residual),
172 .nFunctions = fn->sequenceErrorFunctions_[iFrame].size(),
177double SequenceSolverT<T>::processPerFrameErrors_serial(
184 for (
size_t iFrame = 0; iFrame < fn->getNumFrames(); ++iFrame) {
185 auto jacRes = computePerFrameJacobian(fn, iFrame, skelState, meshState);
186 errorSum += jacRes.error;
188 if (jacRes.usedRows > 0) {
189 qrSolver.addMutating(
190 iFrame * fn->perFrameParameterIndices_.size(),
192 jacRes.jacobian.topRows(jacRes.usedRows), fn->perFrameParameterIndices_),
194 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
195 jacRes.residual.topRows(jacRes.usedRows));
199 progress->increment(jacRes.nFunctions);
207template <
typename T,
typename Comparator>
211 queue.push_back(std::move(value));
212 std::push_heap(queue.begin(), queue.end(), Comparator());
216 std::pop_heap(queue.begin(), queue.end(), Comparator());
220 [[nodiscard]] T& top() {
221 return queue.front();
224 [[nodiscard]]
bool empty()
const {
225 return queue.empty();
229 std::vector<T> queue;
235double SequenceSolverT<T>::processErrorFunctions_parallel(
236 const std::function<JacobianResidual(
245 const size_t end = fn->getNumFrames();
249 PriorityQueue<JacobianResidual, std::greater<>> reorderBuffer;
250 std::mutex reorderBufferMutex;
252 std::deque<JacobianResidual> readyJacobians;
253 std::mutex readyJacobiansMutex;
254 std::size_t nextToProcess{0};
258 std::mutex qrSolverMutex;
264 std::vector<PerFrameStateT<T>> states;
265 dispenso::parallel_for(
268 dispenso::makeChunkedRange(0, end, 1),
270 for (
size_t iFrame = rangeStart; iFrame < rangeEnd; ++iFrame) {
276 JacobianResidual universalJacRes =
277 processJac(iFrame, fn, qrSolver, state.skeletonState, state.meshState);
280 std::unique_lock<std::mutex> reorderBufferLock(reorderBufferMutex);
281 reorderBuffer.push(std::move(universalJacRes));
285 while (!reorderBuffer.empty() && reorderBuffer.top().frameIndex == nextToProcess) {
287 std::unique_lock<std::mutex> readyJacobiansLock(readyJacobiansMutex);
288 readyJacobians.push_back(std::move(reorderBuffer.top()));
296 std::unique_lock<std::mutex> qrSolverLock(qrSolverMutex, std::try_to_lock);
297 if (qrSolverLock.owns_lock()) {
299 JacobianResidual toProcess;
301 std::unique_lock<std::mutex> lock(readyJacobiansMutex);
302 if (!readyJacobians.empty()) {
303 toProcess = std::move(readyJacobians.front());
304 readyJacobians.pop_front();
308 MT_CHECK(toProcess.usedRows <= toProcess.residual.rows());
310 if (toProcess.frameIndex == SIZE_MAX) {
313 if (toProcess.residual.rows() > 0) {
314 qrSolver.addMutating(
315 toProcess.jacobian.topRows(toProcess.usedRows),
316 toProcess.residual.topRows(toProcess.usedRows));
318 errorSum += toProcess.error;
320 progress->increment(toProcess.nFunctions);
329 std::unique_lock<std::mutex> solverLock(qrSolverMutex);
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));
339 errorSum += readyJacobians.front().error;
341 progress->increment(readyJacobians.front().nFunctions);
343 readyJacobians.pop_front();
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));
355 errorSum += reorderBuffer.top().error;
357 progress->increment(reorderBuffer.top().nFunctions);
369double SequenceSolverT<T>::processPerFrameErrors_parallel(
373 return processErrorFunctions_parallel(
382 auto jacRes = computePerFrameJacobian(fn, iFrame, skelState, meshState);
384 if (jacRes.usedRows > 0) {
385 qrSolver.zeroBandedPart(
386 iFrame * fn->perFrameParameterIndices_.size(),
388 jacRes.jacobian.topRows(jacRes.usedRows), fn->perFrameParameterIndices_),
390 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
391 jacRes.residual.topRows(jacRes.usedRows));
394 if (fn->universalParameterIndices_.empty()) {
397 .frameIndex = iFrame,
398 .jacobian = Eigen::MatrixX<T>(),
399 .residual = Eigen::VectorX<T>(),
400 .error = jacRes.error,
401 .nFunctions = jacRes.nFunctions,
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};
424double SequenceSolverT<T>::processSequenceErrors_serial(
428 if (fn->numTotalSequenceErrorFunctions_ == 0) {
432 const size_t bandwidth = qrSolver.bandwidth() / fn->perFrameParameterIndices_.size();
433 MT_CHECK(qrSolver.bandwidth() % fn->perFrameParameterIndices_.size() == 0);
439 std::vector<SkeletonStateT<T>> skelStates(bandwidth);
440 std::vector<MeshStateT<T>> meshStates(bandwidth);
443 for (
size_t iFrame = 0; iFrame < fn->getNumFrames(); ++iFrame) {
444 const size_t bandwidth_cur = std::min<size_t>(fn->getNumFrames() - iFrame, bandwidth);
448 const size_t numValidFrames = (iFrame == 0) ? 0 : (bandwidth_cur - 1);
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]);
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);
464 if (fn->needsMeshSequence()) {
465 meshStates[kSubFrame].update(
466 fn->frameParameters_[iFrame + kSubFrame], skelStates[kSubFrame], fn->getCharacter());
470 auto jacRes = computeSequenceJacobian(fn, iFrame, bandwidth, skelStates, meshStates);
471 errorSum += jacRes.error;
473 if (jacRes.usedRows > 0) {
474 qrSolver.addMutating(
475 iFrame * fn->perFrameParameterIndices_.size(),
477 jacRes.jacobian.topRows(jacRes.usedRows),
478 std::span(sequenceColumnIndices)
479 .subspan(0, bandwidth_cur * fn->perFrameParameterIndices_.size())),
481 jacRes.jacobian.topRows(jacRes.usedRows), fn->universalParameterIndices_),
482 jacRes.residual.topRows(jacRes.usedRows));
486 progress->increment(jacRes.nFunctions);
500 fn->getNumFrames() * fn->perFrameParameterIndices_.size(),
501 fn->universalParameterIndices_.size(),
502 this->bandwidth_ * fn->perFrameParameterIndices_.size(),
503 std::sqrt(this->regularization_));
505 fn->setFrameParametersFromJoinedParameterVector(this->
parameters_);
507 std::unique_ptr<ProgressBar> progress;
509 progress = std::make_unique<ProgressBar>(
511 fn->numTotalPerFrameErrorFunctions_ + fn->numTotalSequenceErrorFunctions_);
516 this->
error_ += processPerFrameErrors_parallel(fn, qrSolver, progress.get());
519 this->
error_ += processSequenceErrors_serial(fn, qrSolver, progress.get());
521 this->
error_ += processPerFrameErrors_serial(fn, qrSolver, progress.get());
522 this->
error_ += processSequenceErrors_serial(fn, qrSolver, progress.get());
526 const Eigen::VectorX<T> searchDir = qrSolver.
x_dense();
528 const double error_orig = this->
error_;
530 const double innerProd = -qrSolver.
At_times_b().dot(searchDir);
533 const float c_1 = 1e-4f;
534 const float tau = 0.5f;
537 const Eigen::VectorX<T> parameters_orig = this->
parameters_;
538 for (
size_t kStep = 0; kStep < 10 && std::fpclassify(alpha) == FP_NORMAL; ++kStep) {
545 if ((error_orig - error_new) >= c_1 * alpha * -innerProd) {
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
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().
VectorType At_times_b() const
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.
const Character & getCharacter() const
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.
double error_
Current objective function value.
SolverFunctionT< T > * solverFunction_
Function to be optimized.
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()
Represents the complete state of a model's mesh.
void update(const ModelParametersT< T > ¶meters, 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.