Skip to content

NonsmoothNewton: parallel kernels and reuse of the symbolic analysis - #129

Open
Kaiyao-Ge wants to merge 13 commits into
polyfem:mainfrom
Kaiyao-Ge:parallel-nonsmooth
Open

Kaiyao-Ge wants to merge 13 commits into
polyfem:mainfrom
Kaiyao-Ge:parallel-nonsmooth

Conversation

@Kaiyao-Ge

@Kaiyao-Ge Kaiyao-Ge commented Nov 13, 2026 •

Copy link
Copy Markdown

NonsmoothNewton: parallel kernels and reuse of the symbolic analysis

Stacked on #123: the first commits of this branch are #123; review the last five.

Single-thread results are bitwise unchanged. The work is split so each commit can be judged on its own:

  1. Newton: reuse the symbolic analysis while the Hessian pattern is unchanged. Platform code: every Newton-type strategy benefits, not only NonsmoothNewton.
  2. NonsmoothNewton: keep the symbolic analysis after a failed factorization, so the projected retry does not analyze again.
  3. Thread-parallel sparse products and sums (ParallelKernels.{hpp,cpp}), equal to Eigen's results bit for bit for any thread count. New option POLYSOLVE_WITH_TBB (default ON).
  4. Parallel reduction of the contact blocks in the model. The blocks are summed in chunks whose number depends only on the number of blocks. With one thread the loop is the old one; with several threads the sum rounds differently from one thread but does not depend on the thread count.
  5. Reuse of basis products and block buffers in the inner steps.

Tests: newton-analysis-reuse (the reused analysis gives the same directions as a fresh strategy, also after a failed factorization) and parallel-kernels (1/2/3/8 threads against Eigen). A differential driver over 136 solves of small problems gave byte-identical output single-threaded, and identical output for 2, 4 and 8 threads.

Effect, measured with an earlier version of these changes together with the PolyFEM side (polyfem/polyfem#563), 6 threads, one run each:

  • NonsmoothNewton: octocat-bowl 867 s → 524 s; golf-ball, frames 1–106, 857 s → 774 s.
  • Newton chain alone (benefits from 1 and the PolyFEM caches): 1935 s → 1667 s and 1093 s → 925 s.

Near convergence the true decrease of a path falls below what the energy
can resolve, so the acceptance test can no longer verify it. Two options
(spec and Options):

- handoff (off | first | any, default any): after an outer iteration whose
  inner loop stopped at the noise floor or whose path is below the
  resolution (first: only if no inner step was accepted before), and when
  the gradient norm is below line_search/use_grad_norm_tol, the rest of the
  solve is left to the Newton chain. A declined direction is not counted
  as a failure. Counters handoff_noise_floor, handoff_grad_norm and
  handoff_iterations in the solver info.
- resolution (default true): 32 eps |E| counts in the inner noise floor,
  and a path whose model decrease does not exceed it is not verified by
  the true energy (the Newton step is line searched instead).

Tests: option parsing; the log-barrier problem with and without the
handoff; fewer retractions and true energy evaluations with the
resolution on an energy with a large constant.
NonsmoothNewton needs an LLT that reports indefinite matrices, which so far
meant Eigen::CholmodSupernodalLLT only, so builds without CHOLMOD could not
run the strategy at all.

Eigen's SimplicialLLT reports a non-positive pivot as NumericalIssue, which
EigenDirect turns into the same runtime_error the strategy already catches.
Add it as a linear solver (factory, available_solvers, spec) and let
NonsmoothNewton accept it. The log-term test now runs in every build, with
CHOLMOD when available and SimplicialLLT otherwise, and also checks a solve
with SimplicialLLT.
…h's norm

The handoff to the Newton chain on a small gradient compared the gradient
norm, in the norm type passed to the strategy, with
line_search/use_grad_norm_tol. The line search makes the same comparison
in solver_params/norm_type, with its rescaling, to decide when to compare
gradient norms instead of energies. Read norm_type the same way the line
search does, so the handoff happens where the line search switches.

This changes the solution path on every contact scene we ran. Wall time
over the contact frames (Intel i7-10700K, single thread, two candidate
orderings): octocat-bowl 9.3% slower, mat-twist 0.5% slower, pin-cushion
ball 8.0% faster.
A strategy that leaves iterations to the strategies behind it (NonsmoothNewton
hands the rest of a solve to the Newton chain) cannot see what those
iterations achieve. Add DescentStrategy::chain_step_result: at the start of
the iteration after a step taken with the line search by any strategy other
than the first, Solver::minimize calls it on the first strategy with the index
of that strategy, the step size of its line search, the energy and gradient
norm before and after the step, and the gradient tolerance of the stopping
test. The call comes after the energy and gradient at the new iterate are
computed and before the convergence check, so the step that ends the solve is
reported too.

The default does nothing; no solve changes. Test: a first strategy that
declines every direction sees each step of the Newton chain, with energies and
gradient norms that match from one step to the next.

The log-term test problem also brings Problem::hessian into scope, which
silences -Woverloaded-virtual for its sparse override.
After a handoff on a small gradient the Newton chain finishes the solve. The
gradient threshold of the handoff does not tell whether Newton converges fast
from there: on golf-ball frame 73, the eight full Newton steps after the
handoff reduced the gradient norm only 4.0 to 4.6 times each, at one
factorization per step (the rate of Newton at a double root).

New option hand_back (spec and Options, off by default): after a handoff on a
small gradient, the first chain step that ends above the gradient tolerance,
removes more than hand_back/energy (100) times the energy resolution
32 eps |E|, and is slow hands the iterations back to NonsmoothNewton. A step
is slow if its line search cut it, if a strategy at index >= 2 of the solver
took it (behind Newton: projected Newton or later), or if it reduced the
gradient norm less than hand_back/contraction (10) times. The handoff on a
small gradient is then off for the rest of the solve, so there is at most one
hand-back per solve; a handoff after a noise-floor stop is never handed back.
The rule reads the chain step report of the previous commit. Counter
hand_backs in the solver info.

With max_inner 40 (two candidate orderings each), the hand-back cut the
factorizations on golf-ball from 908 to 662 and 663 over frames 1-200, and on
frames 73-100 from 233 and 235 to 150 and 152. On mat-twist 20k and 45k,
trash-compactor and rod-twist it cut them to 0.44-0.83 of the count without
it; on ball-rollers it added about 1%.

Tests: option parsing; each of the three signs of a slow step hands back on
its own; a converged step, an energy decrease below the threshold, a fast full
Newton step, the option off, no handoff, and a handoff at the noise floor do
not.
The inner model keeps the smooth part at its quadratic at the outer iterate.
For an energy term -log J, once an outer iteration needs an element
compressed below half its volume, the minimizer of that element's quadratic
is an inverted configuration, so long paths crush small elements. The ratio
test does not see it, because their energy is tiny; the next outer iteration
pays with an indefinite B. On golf-ball impact frames with max_inner 40, the
median smallest det F at the accepted points was 0.006.

Two optional Problem callbacks: smooth_min_jacobian(x), the smallest element
volume ratio J = det F at x, and smooth_min_jacobians(x, y, ...), the smallest
J at y and the smallest ratio J_e(y) / J_e(x) over the elements, in one sweep.
Both default to NaN (not available).

Two options under jacobian (spec and Options; 0 = off, the default):
- bound: every element keeps J_e(y) >= bound * J_e(x) at the end point y of
  every inner step, x the outer iterate;
- floor: min J(y) >= floor * J_ref, or >= min J(x) where x is already below
  that. J_ref is min J at the first iterate of the solve whose direction
  request the strategy does not decline by the handoff.
Both are checked after the Armijo test of a step. A later step that violates
one is not taken and the path ends at the previous point; a first step is
halved further (at most 40 times) until both limits and the Armijo test hold,
and the path ends after it. A limit is not applied where the problem gives
NaN; that is logged once per solve at debug level, since it is a property of
the problem and every time step and AL stage is a solve. Counters
jacobian_bound_hits and jacobian_floor_hits.

With the bound at 0.6 (max_inner 40, same batch), the projected outer
iterations on golf-ball impact frames went from 33 and 34 (two candidate
orderings) to 0. The floor caps the compression that accumulates over outer
iterations and rarely acts: 22 and 19 times on pin-cushion, 3 and 2 on
ball-rollers, never on octocat-bowl, golf-ball and mat-twist 3.2k.

Tests: option parsing; on the log-term problem with its coordinates as
elements, a first step shortened to the bound, a later step that ends the
path, the floor with its reference from the first direction of the solve and
at an iterate already below it, a problem without the callbacks taking the
path of the limits off, and a whole solve with both limits.
The defaults become the configuration the method was benchmarked with, so
that "solver": "NonsmoothNewton" alone runs it:
- max_inner 40 (was 10);
- jacobian/bound 0.6 and jacobian/floor 0.1;
- hand_back/enabled true, with energy 100 and contraction 10.
Each part can still be switched off (jacobian/bound 0, jacobian/floor 0,
hand_back/enabled false) or set back (max_inner 10).

max_inner 40 is the budget of the benchmark, not a value found best on every
scene: under earlier configurations of the method, octocat-bowl was fastest
at 40 in a scan from 5 to 100, while golf-ball ran faster with 5 than with
40. The Jacobian limits act only on problems that implement
Problem::smooth_min_jacobian(s).

This changes the solution path of solves whose paths run past 10 inner
steps, reach a Jacobian limit or hand off on a small gradient; the previous
two commits give the effect of the limits and of the hand-back on their own.

The option test checks the new defaults, and that the defaults Solver::create
fills in from the spec are those of Options.
…anged

Newton, ProjectedNewton and RegularizedNewton analyzed the sparsity
pattern of the Hessian before every factorization. With
Eigen::CholmodSupernodalLLT, Eigen::SimplicialLLT and
Eigen::SimplicialLDLT the analysis (fill-reducing ordering and symbolic
factorization) depends on the pattern alone, so it is now redone only
when the pattern differs from the one of the last analysis. A failed
numeric factorization leaves the analysis valid, so the next Hessian
with the same pattern reuses it too. Other linear solvers analyze before
every factorization as before.

This is shared code, not part of NonsmoothNewton: every Newton chain
with one of these solvers takes this path, the plain Newton solver and
the chain behind NonsmoothNewton included. The numeric factorization of
a kept analysis gives the factor of a fresh one, so no solve changes.

Test: with each of the three solvers, a strategy that keeps its analysis
over a sequence of points with the same Hessian pattern, one of them
indefinite (failed factorization), gives the directions of a new
strategy at every point, bit for bit.
The strategy skipped the symbolic analysis when B had the pattern of the
last successful factorization, but dropped the analysis when a numeric
factorization failed. The analysis depends on the pattern alone, so it
stays valid: the projected retry of an outer iteration (B = proj(H_s) +
proj(H_n) after B = H_s + proj(H_n) failed) usually has the same pattern
and now reuses it. No solve changes.
…gen's

Several steps of every outer iteration and inner step ran in one thread:
the sums B = H_s + proj(H_n), the product H_s q for each new column of
the basis and its dot products with the basis (a column of G), the
residual H d + g of the direction, and the sparse products in the
residual of each new column. They now use kernels in ParallelKernels
that split the work over the threads allowed by tbb::global_control
(PolyFEM sets it from solver/max_threads) and give the results of the
Eigen expressions they replace bit for bit, with any number of threads:
- y += H (alpha q) splits the rows over the threads; every entry adds
  its terms in column order with the operations of Eigen's sparse-dense
  product. Where Eigen folds r = v - H p into r = v, then r -= H p, the
  callers do the same.
- C = A + B merges the columns in two passes split over the columns:
  the union of the patterns, a + b, and a + 0 or 0 + b for an entry of
  one operand only, as Eigen's sum does.
- the dot products of a new column with the basis are split over the
  columns of the basis.
With one thread everything runs in the caller.

TBB becomes an explicit optional dependency, POLYSOLVE_WITH_TBB (on by
default; TBB was already built whenever MKL uses its TBB threading
layer, the default). The kernels used __has_include in the experiment
code, so they silently ran serially in builds without TBB in the include
path; without the option they now run serially by design.

Test: the kernels against Eigen on 24593 x 24593 random sparse matrices
(empty columns, signed zeros, an uncompressed operand, a column of a
dense matrix as output) with 1, 2, 3 and 8 threads allowed: the same
bits.
With local Hessian blocks, the model's matrix A = G + sum_b L_b^T H_b L_b
(L_b the rows of the basis Q of block b) added one small product per
contact block in one thread, thousands per evaluation on contact-rich
scenes, each through MKL's threading dispatch.

With more than one thread allowed and at least 128 blocks, the blocks
now form contiguous chunks of at least 64 blocks, at most 64 chunks; the
number of chunks depends only on the number of blocks. Each chunk sums
its products with MKL sequential, and the chunk sums are added in chunk
order, the first starting from G.

With one thread, or fewer than 128 blocks, the loop is the one before,
so one-thread results do not change. With several threads the sum
rounds differently from the one-thread sum, but the result does not
depend on the number of threads. (The experiment code used one chunk per
thread, so its results changed with the thread count.)
…steps

An inner step formed Q (z + dz) or x + Q (z + dz) anew for each use (the
guard, the validity check, the fraction-to-boundary rule, the segment
end, the first trial point and the accepted point) and Q z again at the
start of the next step. Each product is now formed once while dz is
unchanged and reused only where the expression it replaces has the same
operands: Eigen evaluates Q v as zero, then += Q v, but x + Q v as x,
then += Q v, which round differently, so one form never stands in for
the other. The first trial point (alpha = 1, and z + 1 dz is z + dz
exactly) reuses x + Q (z + dz); an accepted full step reuses Q (z + dz)
as its point and, while no column was added, as the start of the next
step.

The derivative evaluations of the accepted points also reuse the block
vector of the state they replace instead of allocating a new one; the
problem still receives an empty vector.

No solve changes.

Effect of this series together with the PolyFEM changes of the same
pull request, measured as one change on the experiment code. That code
also restructured the Jacobian check (already part of the earlier
commits), split the model reduction into one chunk per thread, and ran a
validity check of an experiment baseline in parallel, so the numbers are
for the whole set:
- One thread (Intel i7-10700K, pinned, MKL_CBWR=COMPATIBLE, other jobs on
  the sibling hyperthreads): the same trajectories, frame by frame. Wall
  time new / old: 0.999 for the Newton chain alone on golf-ball (both
  runs started together); 0.922 on octocat-bowl and 1.015 on mat-twist
  20k for the method, 1.012 and 1.005 after correcting for the load by
  the time per factorization; 1.134 on golf-ball, where the two runs
  started 2.5 h apart under different load (1.016 over frames 1-20,
  where the load was the same).
- Six threads (AMD Ryzen 5 9600X, one run at a time): octocat-bowl
  1935 -> 1667 s for the Newton chain alone, 809 -> 569 s for the method
  without the Jacobian limits and 867 -> 524 s with them (the old run
  overlapped other jobs); golf-ball frames 1-106, 1093 -> 925 s for the
  Newton chain alone and 857 -> 774 s for the method with the limits.
- Eight threads (i7-10700K shared with another user's eight processes,
  same batch): the method with the limits took 0.63 (octocat-bowl) and
  0.95 (golf-ball) of the old wall time.
"The method" ran with max_inner 40 and an earlier hand-back rule; "the
Newton chain alone" is NonsmoothNewton with the method off, behind the
contact term's certified step bound and fast validity check.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant