Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
gauss_newton_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
13
14#include <gsl/narrow>
15
16namespace momentum {
17
18template <typename T>
20 : SolverT<T>(options, solver) {
21 // Set default values from GaussNewtonSolverOptions
22 doLineSearch_ = GaussNewtonSolverOptions().doLineSearch;
23 regularization_ = GaussNewtonSolverOptions().regularization;
25 targetRowsPerChunk_ = GaussNewtonSolverOptions().targetRowsPerChunk;
26
27 // Update values based on provided options
28 setOptions(options);
29}
30
31template <typename T>
32std::string_view GaussNewtonSolverT<T>::getName() const {
33 return "GaussNewton";
34}
35
36template <typename T>
39
40 if (const auto* derivedOptions = dynamic_cast<const GaussNewtonSolverOptions*>(&options)) {
41 regularization_ = derivedOptions->regularization;
42 doLineSearch_ = derivedOptions->doLineSearch;
43 useBlockJtJ_ = derivedOptions->useBlockJtJ;
44 targetRowsPerChunk_ = derivedOptions->targetRowsPerChunk;
45 }
46}
47
48template <typename T>
50 // This is called from the solver base class .solve()
51
52 // Build enabled parameters mapping from activeParameters_ bitset
53 updateEnabledParameters();
54}
55
56template <typename T>
57void GaussNewtonSolverT<T>::updateEnabledParameters() {
58 enabledParameters_.clear();
59 enabledParameters_.reserve(this->numParameters_);
60
61 for (int i = 0; i < gsl::narrow_cast<int>(this->numParameters_); ++i) {
62 if (this->activeParameters_.test(i)) {
63 enabledParameters_.push_back(i);
64 }
65 }
66}
67
68template <typename T>
69void GaussNewtonSolverT<T>::computeJtJFromBlockJtJ() {
70 MT_PROFILE_EVENT("Get JtJ and JtR");
71
72 // getJtJR() returns JtJ sized up to the highest enabled parameter index (actualParameters_).
73 // It doesn't compact the parameters - gaps between enabled parameters still have entries.
74 // We do in-place row/column shifting to avoid allocating a temporary matrix.
75 this->error_ = this->solverFunction_->getJtJR(this->parameters_, hessianApprox_, JtR_);
76
77 // Compact JtR in-place: shift enabled parameter entries to the front
78 const int nSubsetParams = gsl::narrow_cast<int>(enabledParameters_.size());
79 for (int iSubset = 0; iSubset < nSubsetParams; ++iSubset) {
80 const int iFull = enabledParameters_[iSubset];
81 if (iFull > iSubset) {
82 JtR_(iSubset) = JtR_(iFull);
83 }
84 }
85
86 // Compact JtJ in-place: shift rows and columns for enabled parameters to the top-left
87 // Process in order so we don't overwrite data we still need (since iFull >= iSubset always)
88 for (int iSubset = 0; iSubset < nSubsetParams; ++iSubset) {
89 const int iFull = enabledParameters_[iSubset];
90
91 // First, copy the column from iFull to iSubset (for rows 0 to iSubset that are already shifted)
92 if (iFull > iSubset) {
93 for (int jSubset = 0; jSubset <= iSubset; ++jSubset) {
94 const int jFull = enabledParameters_[jSubset];
95 // Copy from (jFull, iFull) to (jSubset, iSubset) - but jFull row is already at jSubset
96 hessianApprox_(jSubset, iSubset) = hessianApprox_(jFull, iFull);
97 }
98
99 // Copy the row from iFull to iSubset (for columns 0 to iSubset-1 that are already shifted)
100 for (int jSubset = 0; jSubset < iSubset; ++jSubset) {
101 const int jFull = enabledParameters_[jSubset];
102 // Copy from (iFull, jFull) to (iSubset, jSubset) - but jFull col is already at jSubset
103 hessianApprox_(iSubset, jSubset) = hessianApprox_(iFull, jFull);
104 }
105 }
106 }
107}
108
109template <typename T>
110void GaussNewtonSolverT<T>::computeJtJFromJacobianBlocks() {
111 const int nSubsetParams = gsl::narrow_cast<int>(enabledParameters_.size());
112
113 // Allocate and zero JtJ and JtR for subset parameters
114 hessianApprox_.setZero(nSubsetParams, nSubsetParams);
115 JtR_.setZero(nSubsetParams);
116
117 this->solverFunction_->initializeJacobianComputation(this->parameters_);
118
119 const size_t numBlocks = this->solverFunction_->getJacobianBlockCount();
120
121 // Calculate block sizes and find the maximum block size
122 std::vector<size_t> blockSizes(numBlocks);
123 size_t maxBlockSize = 0;
124 size_t totalRows = 0;
125 for (size_t i = 0; i < numBlocks; ++i) {
126 blockSizes[i] = this->solverFunction_->getJacobianBlockSize(i);
127 maxBlockSize = std::max(maxBlockSize, blockSizes[i]);
128 totalRows += blockSizes[i];
129 }
130
131 // Effective target: at least the largest block, or all rows if targetRowsPerChunk_ is SIZE_MAX
132 const size_t effectiveTarget =
133 (targetRowsPerChunk_ == SIZE_MAX) ? totalRows : std::max(targetRowsPerChunk_, maxBlockSize);
134
135 double error = 0.0;
136
137 // Process blocks in chunks using greedy bin-packing
138 size_t blockIdx = 0;
139 while (blockIdx < numBlocks) {
140 // Determine which blocks go into this chunk
141 size_t chunkRows = 0;
142 size_t chunkStartBlock = blockIdx;
143
144 // Greedily add blocks until we exceed the target
145 while (blockIdx < numBlocks) {
146 const size_t blockSize = blockSizes[blockIdx];
147 if (blockSize == 0) {
148 ++blockIdx;
149 continue;
150 }
151
152 // Add this block if: chunk is empty OR adding it doesn't exceed target
153 if (chunkRows == 0 || chunkRows + blockSize <= effectiveTarget) {
154 chunkRows += blockSize;
155 ++blockIdx;
156 } else {
157 break;
158 }
159 }
160
161 if (chunkRows == 0) {
162 continue;
163 }
164
165 // Resize Jacobian storage for this chunk (ResizeableMatrix avoids reallocations)
166 jacobian_.resizeAndSetZero(chunkRows, this->numParameters_);
167 residual_.resizeAndSetZero(chunkRows);
168
169 // Fill the chunk with block data
170 size_t rowPos = 0;
171 for (size_t i = chunkStartBlock; i < blockIdx; ++i) {
172 const size_t blockSize = blockSizes[i];
173 if (blockSize == 0) {
174 continue;
175 }
176
177 auto jacBlock = jacobian_.mat().block(rowPos, 0, blockSize, this->numParameters_);
178 auto resBlock = residual_.vec().segment(rowPos, blockSize);
179
180 size_t actualRows = 0;
181 error += this->solverFunction_->computeJacobianBlock(
182 this->parameters_, i, jacBlock, resBlock, actualRows);
183 MT_CHECK(
184 actualRows <= blockSize,
185 "Jacobian block {} used {} rows but only {} rows were allocated",
186 i,
187 actualRows,
188 blockSize);
189
190 rowPos += actualRows;
191 }
192
193 if (rowPos == 0) {
194 continue;
195 }
196
197 auto activeJacobianRows = jacobian_.mat().topRows(rowPos);
198
199 // Remap columns to subset parameter space (in-place, similar to SubsetGaussNewtonSolver)
200 // Move the enabled columns of the Jacobian into place.
201 // Doing this in-place minimizes total work.
202 // For the common case where all "dropped" parameters are at the end,
203 // this will effectively be a no-op since enabledParameters_[iSubsetParam] == iSubsetParam.
204 for (int iSubsetParam = 0; iSubsetParam < nSubsetParams; ++iSubsetParam) {
205 if (enabledParameters_[iSubsetParam] > iSubsetParam) {
206 activeJacobianRows.col(iSubsetParam) =
207 activeJacobianRows.col(enabledParameters_[iSubsetParam]);
208 }
209 }
210
211 // Accumulate JtJ and JtR for this chunk
212 const auto J_chunk = activeJacobianRows.leftCols(nSubsetParams);
213 const auto r_chunk = residual_.vec().head(rowPos);
214
215 hessianApprox_.template triangularView<Eigen::Lower>() += J_chunk.transpose() * J_chunk;
216 JtR_.noalias() += J_chunk.transpose() * r_chunk;
217 }
218
219 this->solverFunction_->finalizeJacobianComputation();
220 this->error_ = error;
221}
222
223template <typename T>
226
227 const int nSubsetParams = gsl::narrow_cast<int>(enabledParameters_.size());
228
229 // Compute JtJ and JtR using either pre-computed JtJ or Jacobian blocks
230 // Each code path handles its own matrix sizing
231 if (useBlockJtJ_) {
232 computeJtJFromBlockJtJ();
233 } else {
234 computeJtJFromJacobianBlocks();
235 }
236
237 // Solve for delta in subset parameter space
238 // For BlockJtJ, hessianApprox_ may be larger than nSubsetParams but the compacted
239 // data is in the top-left corner. For Jacobian blocks, it's exactly nSubsetParams.
240 {
241 MT_PROFILE_EVENT("Dense gauss newton step");
242
243 // Get the relevant portion of the matrices
244 auto jtjBlock = hessianApprox_.topLeftCorner(nSubsetParams, nSubsetParams);
245 auto jtrBlock = JtR_.head(nSubsetParams);
246
247 // Add regularization
248 jtjBlock.diagonal().array() += regularization_;
249
250 // Solve
251 Eigen::VectorX<T> subsetDelta = llt_.compute(jtjBlock).solve(jtrBlock);
252
253 // Map subset delta back to full parameter space
254 Eigen::VectorX<T> delta = Eigen::VectorX<T>::Zero(this->numParameters_);
255 for (int iSubsetParam = 0; iSubsetParam < nSubsetParams; ++iSubsetParam) {
256 delta(enabledParameters_[iSubsetParam]) = subsetDelta(iSubsetParam);
257 }
258
259 updateParameters(delta);
260 }
261
262 // Store history (if enabled)
263 {
264 MT_PROFILE_EVENT("Store history");
265 if (this->storeHistory) {
266 auto& jtjHist = this->iterationHistory_["jtj"];
267 if (jtjHist.rows() !=
268 gsl::narrow_cast<Eigen::Index>(this->actualParameters_ * this->getMaxIterations()) ||
269 jtjHist.cols() != gsl::narrow_cast<Eigen::Index>(this->actualParameters_)) {
270 jtjHist.resize(this->actualParameters_ * this->getMaxIterations(), this->actualParameters_);
271 }
272 jtjHist.block(
273 this->iteration_ * this->actualParameters_,
274 0,
275 this->actualParameters_,
276 this->actualParameters_) =
277 hessianApprox_.topLeftCorner(this->actualParameters_, this->actualParameters_);
278 }
279 }
280}
281
282template <typename T>
283void GaussNewtonSolverT<T>::updateParameters(Eigen::VectorX<T>& delta) {
284 if (!doLineSearch_) {
285 MT_PROFILE_EVENT("Update params");
286 this->solverFunction_->updateParameters(this->parameters_, delta);
287 return;
288 }
289
290 MT_PROFILE_EVENT("Line search");
291
292 static constexpr T kC1 = 1e-3;
293 static constexpr T kTau = 0.5;
294 static constexpr size_t kMaxLineSearchSteps = 10;
295
296 const T scaledError = kC1 * this->error_;
297 const Eigen::VectorX<T> parametersOrig = this->parameters_;
298 T lineSearchScale = 1.0;
299
300 for (size_t i = 0; i < kMaxLineSearchSteps && std::isnormal(lineSearchScale); ++i) {
301 this->parameters_ = parametersOrig;
302
303 this->solverFunction_->updateParameters(this->parameters_, lineSearchScale * delta);
304
305 const double errorNew = this->solverFunction_->getError(this->parameters_);
306 if ((this->error_ - errorNew) >= lineSearchScale * scaledError) {
307 break;
308 }
309
310 // Reduce step size:
311 lineSearchScale *= kTau;
312 }
313}
314
315template class GaussNewtonSolverT<float>;
316template class GaussNewtonSolverT<double>;
317
318} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Dense implementation of the Gauss-Newton optimization algorithm.
GaussNewtonSolverT(const SolverOptions &options, SolverFunctionT< T > *solver)
Creates a solver with the specified options and function to optimize.
void setOptions(const SolverOptions &options) final
Updates solver configuration, handling both base and Gauss-Newton specific options.
void initializeSolver() final
Initializes solver state before optimization begins.
void doIteration() final
Performs one iteration of the Gauss-Newton algorithm.
std::string_view getName() const override
Returns "GaussNewton" as the solver name.
Abstract base class for optimization objective functions.
virtual void setOptions(const SolverOptions &options)
Updates solver configuration with new options.
Definition solver.cpp:32
std::unordered_map< std::string, Eigen::MatrixX< T > > iterationHistory_
Recorded data from optimization process.
Definition solver.h:137
size_t getMaxIterations() const
Returns the maximum number of iterations before terminating.
Definition solver.cpp:156
size_t iteration_
Current iteration count.
Definition solver.h:123
bool storeHistory
Whether to record optimization progress for analysis.
Definition solver.h:132
size_t numParameters_
Total number of parameters in the optimization problem.
Definition solver.h:103
SolverT(const SolverOptions &options, SolverFunctionT< T > *solver)
Constructor with solver options and function to optimize.
Definition solver.cpp:20
int actualParameters_
Number of parameters currently enabled for optimization.
Definition solver.h:115
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_EVENT(NAME)
Definition profile.h:112
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
float regularization
Damping parameter added to Hessian diagonal for numerical stability; see https://en....
bool doLineSearch
Enables backtracking line search to ensure error reduction at each step.
Extended options specific to the Gauss-Newton optimization algorithm.
bool useBlockJtJ
Uses pre-computed JᵀJ and JᵀR from the solver function.
size_t targetRowsPerChunk
Target number of Jacobian rows to accumulate before computing JᵀJ.
Common options for numerical optimization solvers.
Definition solver.h:19