newton_cg#

t3toolbox.backend.optimizers.newton_cg(problem, x0, max_newton=30, gtol_rel=1e-08, cg_maxiter=200, c_armijo=0.0001, on_line_search_failure='stop', hessian='gauss_newton', curvature_damping=None, step_control=None, tr_radius0=None, g0_reference=None, g0norm_newton=None, g0norm_cg=None, cg_forcing_power=0.5, use_jit=False, callback=None, *, start_frame=None, padded_from=None, padded_oversampling=None, padded_oversampled_passes=None, padded_max_passes=None, padded_tol=None, padded_alternate=None, padded_seed=None, cone_oversampling=None, cone_oversampled_passes=None, cone_max_passes=None, cone_tol=None, cone_alternate=None, cone_seed=None, timing=False, switch_tau=None, switch_k=None, switch_cg_forcing_power=None, switch_track=None)#
def newton_cg(
        problem:                Problem,  # the fixed-rank least-squares problem
        x0:                     Tangent,  # initial cores (B, G)

        max_newton:             int   = 30,    # Newton iterations (history rows) -- rejected trust-region trials included
        gtol_rel:               float = 1e-8,  # stop when ‖g‖ <= gtol_rel * ‖g0‖  (‖g0‖: g0norm_newton, else the g0_reference)
        cg_maxiter:             int   = 200,
        c_armijo:               float = 1e-4,  # Armijo constant (line search only)
        on_line_search_failure: str = 'stop',  # Armijo exhausted (40 halvings): 'stop' = reject the step and terminate; 'accept' = take the last trial and continue

        hessian:                str   = 'gauss_newton',      # or 'exact' | 'switch' (case-insensitive): the Hessian; 'switch' = GN, then exact
        curvature_damping:      typ.Optional[float] = None,  # exact / switch only: the lift damping, relative to ‖X‖; None = the geometry's default
        step_control:           typ.Optional[str]   = None,  # None = 'line_search' (GN) / 'trust_region' (exact, switch); either works with either
        tr_radius0:             typ.Optional[float] = None,  # trust region only: Δ0 > 0; None = the GN Cauchy length ‖g‖³/⟨g, H_GN g⟩

        g0_reference:           typ.Optional[str]   = None,  # which ‖g0‖: None = the geometry's own ('zero' on manifolds, 'warm_start' on corewise); 'zero' | 'warm_start' | 'cone'
        g0norm_newton:          typ.Optional[float] = None,  # explicit ‖g0‖ for the Newton stop (wins; > 0). Also feeds CG unless g0norm_cg set.
        g0norm_cg:              typ.Optional[float] = None,  # explicit ‖g0‖ for the CG forcing term (wins for CG; > 0); default = the Newton reference

        cg_forcing_power:       float = 0.5,    # η = min(0.5, (‖g‖/‖g0‖)**power); larger => tighter CG, fewer Newton steps
        use_jit:                bool  = False,  # jit the inner CG (lax.while_loop) when the inputs are jax; else eager

        callback:               typ.Optional[typ.Callable] = None,  # callback(NewtonInfo) each iteration (host-side; e.g. a display)
        *,
        start_frame:                typ.Any = None,             # a frame of x0 for iteration 0 (structurally checked)
        padded_from:                typ.Any = None,             # the old point: start_frame = padded_start(problem, x0, padded_from, padded_*)

        padded_oversampling:        typ.Optional[int]   = None, # None = 5    (padded_from only, else a structural error)
        padded_oversampled_passes:  typ.Optional[int]   = None, # None = 2
        padded_max_passes:          typ.Optional[int]   = None, # None = 10
        padded_tol:                 typ.Optional[float] = None, # None = 0.05
        padded_alternate:           typ.Optional[bool]  = None, # None = True
        padded_seed:                typ.Optional[int]   = None, # None = ZERO_FRAME_SEED

        cone_oversampling:          typ.Optional[int]   = None, # None = 5    (g0_reference='cone' without g0norm_newton only, else a structural error)
        cone_oversampled_passes:    typ.Optional[int]   = None, # None = 2
        cone_max_passes:            typ.Optional[int]   = None, # None = 10
        cone_tol:                   typ.Optional[float] = None, # None = 0.05
        cone_alternate:             typ.Optional[bool]  = None, # None = True
        cone_seed:                  typ.Optional[int]   = None, # None = ZERO_FRAME_SEED

        timing:                     bool = False,               # NewtonInfo.timing per row, stats['timing'] per run

        switch_tau:                 typ.Optional[float] = None, # None = 0.25; in [0, 1); 0 = never switch (hessian='switch' only, else a structural error)
        switch_k:                   typ.Optional[int]   = None, # None = 2; an int >= 0; 0 = exact from iteration 0
        switch_cg_forcing_power:    typ.Optional[float] = None, # None = 1.0: the forcing power from the switch on
        switch_track:               typ.Optional[str]   = None, # None = 'countable'; 'countable' | 'all': the rows that track
) -> typ.Tuple[Tangent, dict]:      # (x_cores, stats)

Inexact Riemannian Newton-CG – the manifold workhorse. Each Newton step builds the local model once, solves H p = −g by (Steihaug) CG to an inexact forcing-term tolerance (the inner loop – jit-able via _cg_solve()), then controls the step by a line search or a trust region. use_jit jits only the inner CG (the outer loop, step control, and convergence test stay on the host), auto-converting numpy inputs to jax first (_prepare_jit_inputs()) – so a use_jit=True call on numpy data returns a jax-backed result (jax’s default float32 unless x64 is enabled); if jax is not installed it runs eager with a warning.

The Hessian (hessian). 'gauss_newton' (default): H = Π 𝒥ᵀω²𝒥 Π (+ the regularizer’s), positive semidefinite – the gauged H is positive-definite on the manifold, and CG truncates on the gauge-singular corewise H. 'exact': the exact Riemannian Hessian, which adds the curvature term Π Lᵀ(K_{Aᵀω²r} − K_{grad f}) L Π (Problem.local_model(); it needs a kind implementing corewise_hessian and a geometry with the four exact-mode members). Gauss-Newton converges linearly at a rate set by that missing term (|1 − ρ| measures it); the exact Hessian gives the superlinear Newton tail – q-quadratic with cg_forcing_power=1.0, order about 1.5 at the default 0.5. It costs a few times a Gauss-Newton Hessian-apply. curvature_damping (exact and switch only; a value with Gauss-Newton raises) is the lift’s damping relative to ‖X‖, None for the geometry’s own default. 'switch' starts with Gauss-Newton and switches to the exact Hessian within the run (below).

Switching from Gauss-Newton to the exact Hessian (hessian='switch'; it needs what 'exact' needs, checked at the call). Each point of the Gauss-Newton phase is linearized once in exact mode (one misfit transpose, as in either pure mode, plus the geometry’s curvature data); CG, the step control and the row use its Gauss-Newton view, so the steps are a Gauss-Newton run’s. After a step, e_GN = |Δf − m_GN(s)| (m_GN(s) the row’s predicted change) and, on a countable row, e_N = |Δf − m_N(s)| with m_N(s) = m_GN(s) + ½α²⟨s, Π Lᵀ K_N L Π s⟩ (one curvature product). A countable row with e_N < switch_tau·e_GN (default 0.25) is a hit; switch_k (default 2) consecutive hits switch to the exact Hessian for good, from the next point on: the exact model must have predicted the objective at least four times better, on two clean steps in a row. A row is countable iff it took the full model step (an accepted trust-region trial; an Armijo step with α = 1), so a rejected trial, a backtrack, the −g fallback and a forced 'accept' reset the count, as do a miss and a sample whose two errors are both at the objective’s rounding level, 1000·ε·(‖ω⊙y‖·‖ω⊙r‖ + |f|) (the trust region’s floor times 100; under float32 only large early steps clear it – prefer jax x64); a CG step stopped on the region’s boundary, or truncated, counts like any other. switch_track='all' runs the product on every Gauss-Newton step row (reported, never counted: the switch fires at the same row). The default step control is the trust region, whose radius carries across the switch; cg_forcing_power is the Gauss-Newton phase’s forcing power and switch_cg_forcing_power (default 1.0) the exact phase’s. switch_tau=0 tracks and never switches (the run is the Gauss-Newton run with the same step control, bit for bit, plus the tracking); switch_k=0 is exact from iteration 0 (the exact run with cg_forcing_power=switch_cg_forcing_power). Each call starts in Gauss-Newton: nothing carries across calls, so a continuation level after a rank increase starts there too. It may never fire, safely: the curvature term vanishes (the manifold at d = 1), the residual is zero, or the retraction is only first order at the point (near small singular values, a zero-padded start). Each row records the model that solved it (hessian) and the switch_* fields (NewtonInfo); stats gains three keys (below). A switch_* option without hessian='switch' raises, as does one the run would not read (switch_tau or switch_track with switch_k=0; switch_k or switch_cg_forcing_power with switch_tau=0). The user guide, with a worked run: docs/fitting_and_optimization.md §4.14.

Step control (step_control; the default follows the Hessian, and either combines with either):

  • 'line_search' (the Gauss-Newton default): plain truncated CG, then Armijo backtracking along retract(α p).

  • 'trust_region' (the exact and switch default – the exact H is indefinite away from a minimizer): Steihaug-Toint CG inside ‖p‖ ≤ Δ (it steps to the boundary on nonpositive curvature or when it would leave the region), then one trial retract(p), accepted iff the ratio of the actual to the model’s predicted change ρ = Δf / (gᵀp + ½ pᵀHp) exceeds 0.1. Δ ← ¼‖p‖ when ρ < 0.25 (or not finite); Δ ← min(2Δ, 10⁴Δ0) when ρ > 0.75 on a boundary step. Δ0 = tr_radius0, by default the Gauss-Newton Cauchy length ‖g‖³ / ⟨g, H_GN g⟩. A rejected trial keeps x – and the local model, which is rebuilt only after an accepted step – emits its own history row (tr_accepted=False) and counts toward max_newton. Two floors, checked only after a rejection (an accepted step never stops the run): 'objective_floor' when the predicted change is below the objective’s floating-point resolution, |pred| ≤ 10·ε·(‖ω⊙y‖·‖ω⊙r‖ + |f|) with ε the residual dtype’s machine epsilon – the attainable accuracy is reached, which is not a failure (converged stays False because the gradient test did not fire); else 'trust_region_floor' when Δ has fallen below 10⁻¹²·Δ0. tr_radius0 with 'line_search' raises, as does on_line_search_failure='accept' with 'trust_region' (neither would have an effect).

The reference gradient norm ‖g0‖ (g0_reference / g0norm_newton / g0norm_cg / cg_forcing_power). Both stopping tests are relative to a reference ‖g0‖: the Newton stop is ‖g‖ ≤ gtol_rel·‖g0‖ and the CG forcing term is η = min(0.5, (‖g‖/‖g0‖)**cg_forcing_power). Which reference, resolved once at iteration 0 (docs/fitting_and_optimization.md §5):

  • g0_reference=None (default) – the geometry’s own: 'zero' on a manifold geometry (one with a zero_point_frame), 'warm_start' on a corewise one (the zero cores are a critical point there, so the zero reference would be exactly 0) and on a custom geometry without the member.

  • 'zero' – the gradient norm at the zero tensor of x0’s ranks, evaluated at the canonical zero-point frame (fv_zero_point_frame()): one extra sweep and transpose on this problem. A deterministic data-gradient scale at these ranks, fixed by convention and good to an O(1) factor – comparable across rank-continuation levels and identical on the ragged and uniform layers. It is the right reference after a warm start, whose initial gradient is deflated (the guess is already near the solution). An explicit 'zero' on a geometry with no zero-point frame raises ValueError.

  • 'warm_start' – the initial gradient norm ‖g(x0)‖ (the 2026.2.0 default; 1.0 if it is 0, when x0 is stationary and the stop fires at once).

  • 'cone' – the gradient norm at the zero tensor of x0’s ranks, at the frame there ALIGNED with the data gradient (padded_start() from the zero tensor; the cone_* options, use_jit as below). 'zero' evaluates it at a fixed, data-independent frame, which can miss most of the gradient; cone_max_passes=0 evaluates it at the zero tensor’s hint-free start (random orthonormal cores, a different frame from 'zero'’s). stats['cone_movements'] records the passes.

The start frame (start_frame / padded_from). Iteration 0 linearizes at geom.frame(x0) by default. start_frame gives a frame of x0 instead (structurally checked by the geometry’s require_frame_structure); padded_from=x_old builds it: x0 is x_old zero-padded to the target ranks, whose own frame is arbitrary on the new slots, and padded_start() aligns the new slots with the misfit gradient (the padded_* options; padded_max_passes=0 is the hint-free padded frame). Both need a manifold geometry. use_jit governs the alignment as well as CG. With either keyword, stats['start_frame'] is 'given' or 'padded' and stats['start_movements'] the passes. An option of a group set without its group engaged (padded_* without padded_from, cone_* without 'cone' or with g0norm_newton) raises, as does zero passes with an option they would not read.

A vanishing zero reference (the data gradient at the zero tensor is 0, e.g. all-zero data) is never silently replaced by a constant: by default it falls back to the warm start with a RuntimeWarning; an explicit 'zero' raises ValueError. The explicit overrides then win, with a chained fallback: g0norm_newton sets the Newton reference (and CG inherits it unless g0norm_cg is also given – so with g0norm_newton given the zero reference is not computed at all); g0norm_cg alone sets only the CG reference. A non-positive override raises ValueError. Every history row records the kinds (g0_reference, cg_reference; 'override' for an explicit value). cg_forcing_power (default 0.5, the conventional Eisenstat-Walker value, in both modes) tunes CG effort per Newton step: since ‖g‖/‖g0‖ < 1 near the solution, a larger power (0.75, 1.0) tightens CG -> more CG iterations but fewer Newton steps – worth it on the manifold when the retraction is expensive relative to a Hessian-apply, and 1.0 is what makes the exact Hessian’s tail q-quadratic. The min(0.5, …) cap on η is retained regardless.

Line-search exhaustion (on_line_search_failure). If all 40 Armijo halvings fail, the objective’s floor has been reached (typically deep in a continuation run). The default 'stop' rejects the step and terminates – the conventional reading, and it stops the ~2×40 objective evaluations per stagnant iteration. 'accept' instead takes the last (smallest) trial step and keeps iterating even though it may climb – a deliberate escape mode: on some landscapes the small non-descent step bumps the iterate out of a stagnant region, after which convergence resumes. Either way the iteration’s NewtonInfo row carries ls_failed=True and alpha is the step of the last trial actually evaluated (2^-39), so delta_f / rho / step_rel describe a step that was genuinely tried.

callback, if given, is called with a NewtonInfo each iteration (including the final converged line) – the hook for a live diagnostic display; it runs host-side (it reads the concrete residual), so it composes with use_jit (only the inner CG jits) but not with a hypothetical fully-jitted outer loop. Ready-made displays: t3toolbox.backend.optimizer_display.make_newton_display().

stats is {'losses', 'newton_steps', 'newton_accepted', 'stop_reason', 'history'}: newton_steps counts the CG solves (the history rows that took a step), newton_accepted the steps taken (newton_steps minus the rejections: an Armijo-exhausted one under 'stop', or the rejected trust-region trials), stop_reason is 'gradient' / 'max_newton' / 'line_search' / 'objective_floor' / 'trust_region_floor' (see NewtonInfo), and history is one _newton_scalar_record() per iteration (losses[k] == history[k]['objective']). (The 2026.2.0 stats['newton'] is removed; it is newton_steps.) hessian='switch' adds stats['hessian'] = 'switch', stats['switch_track'] ('countable' or 'all'; None with switch_k=0) and stats['switched_at'], the index of the first row whose model is exact (len(history) when the switch fired on the last row; 0 with switch_k=0; None if it never fired). timing=True adds stats['timing'] (below).

Timing (timing=True; it changes no number). Each row’s wall_time window is split by phase into NewtonInfo.timing (a NewtonTiming; PhaseSeconds lists the phases), with jax’s compile wait per phase on a jax run (None on numpy, and on a jax whose jax.monitoring cannot unregister a listener). stats['timing'] is a plain dict: total, setup, alignment, alignment_passes, reference_passes, last_callback (the last row’s callback, outside every window), phases (each phase summed over the rows), compile (the same for the compile wait, with setup, alignment and last_callback; None as above), cg_per_iteration (CG’s seconds less its compile wait, per CG iteration) and rows (each row’s record as a dict). total == setup + (alignment or 0) + Σ window + last_callback. Every phase ends by waiting on its outputs (jax dispatch is asynchronous), so a timed jax run is serialized and slower than an untimed one; work dispatched without waiting (a callback’s, or -g before CG) is charged to the next phase that waits for it. The compile listener is process-global: compiles in other threads, or in a timed run nested inside a callback, are counted too. A Problem subclass that overrides local_model is called as without timing, and its whole build is reported in frame. The geometry member aligned_padded_frame is asked for its seconds per pass only when its signature names timing (see Geometry). With make_newton_display() as the callback, each row prints a time line and the run ends with a closing table. What each phase covers, what the synchronization costs and how the compile column reads under use_jit and eager jax: the user guide, docs/fitting_and_optimization.md §4.13.

Examples

The exact Hessian with its default trust region, against Gauss-Newton with its default line search, on a noisy probe-derivative fit warm-started near the solution:

>>> import numpy as np
>>> import t3toolbox.tucker_tensor_train as t3
>>> import t3toolbox.backend.fitting as bfit
>>> import t3toolbox.backend.geometry as bgeo
>>> import t3toolbox.backend.optimizers as bopt
>>> np.random.seed(0)
>>> shape, rng = (5, 5, 5), np.random.default_rng(0)
>>> ww, pp = ([rng.standard_normal((40, n)) for n in shape] for _ in range(2))
>>> kind = bfit.ProbeDerivativesKind(order=1)
>>> target = t3.TuckerTensorTrain.randn(shape, (3, 3, 3), (1, 3, 3, 1)).data
>>> data = [z + 0.01 * rng.standard_normal(z.shape) for z in kind.point_forward(target, (ww, pp))]
>>> problem = bopt.least_squares_problem(bgeo.ManifoldGeometryOps(), kind, (ww, pp), data)
>>> x0, _ = bopt.newton_cg(problem, t3.TuckerTensorTrain.randn(shape, (2, 2, 2), (1, 2, 2, 1)).data,
...                        max_newton=5)
>>> _, gn = bopt.newton_cg(problem, x0, max_newton=40, g0_reference='warm_start')
>>> _, ex = bopt.newton_cg(problem, x0, max_newton=40, g0_reference='warm_start',
...                        hessian='exact', cg_forcing_power=1.0)
>>> ex['history'][0]['step_control'], ex['stop_reason'] in ('gradient', 'objective_floor')
('trust_region', True)
>>> gn['newton_steps'] > 2 * ex['newton_steps']     # Gauss-Newton is linear here; exact has the Newton tail
True
Parameters:
  • problem (Problem)

  • x0 (Tangent)

  • max_newton (int)

  • gtol_rel (float)

  • cg_maxiter (int)

  • c_armijo (float)

  • on_line_search_failure (str)

  • hessian (str)

  • curvature_damping (t3toolbox.backend.common.typ.Optional[float])

  • step_control (t3toolbox.backend.common.typ.Optional[str])

  • tr_radius0 (t3toolbox.backend.common.typ.Optional[float])

  • g0_reference (t3toolbox.backend.common.typ.Optional[str])

  • g0norm_newton (t3toolbox.backend.common.typ.Optional[float])

  • g0norm_cg (t3toolbox.backend.common.typ.Optional[float])

  • cg_forcing_power (float)

  • use_jit (bool)

  • callback (t3toolbox.backend.common.typ.Optional[t3toolbox.backend.common.typ.Callable])

  • start_frame (t3toolbox.backend.common.typ.Any)

  • padded_from (t3toolbox.backend.common.typ.Any)

  • padded_oversampling (t3toolbox.backend.common.typ.Optional[int])

  • padded_oversampled_passes (t3toolbox.backend.common.typ.Optional[int])

  • padded_max_passes (t3toolbox.backend.common.typ.Optional[int])

  • padded_tol (t3toolbox.backend.common.typ.Optional[float])

  • padded_alternate (t3toolbox.backend.common.typ.Optional[bool])

  • padded_seed (t3toolbox.backend.common.typ.Optional[int])

  • cone_oversampling (t3toolbox.backend.common.typ.Optional[int])

  • cone_oversampled_passes (t3toolbox.backend.common.typ.Optional[int])

  • cone_max_passes (t3toolbox.backend.common.typ.Optional[int])

  • cone_tol (t3toolbox.backend.common.typ.Optional[float])

  • cone_alternate (t3toolbox.backend.common.typ.Optional[bool])

  • cone_seed (t3toolbox.backend.common.typ.Optional[int])

  • timing (bool)

  • switch_tau (t3toolbox.backend.common.typ.Optional[float])

  • switch_k (t3toolbox.backend.common.typ.Optional[int])

  • switch_cg_forcing_power (t3toolbox.backend.common.typ.Optional[float])

  • switch_track (t3toolbox.backend.common.typ.Optional[str])

Return type:

t3toolbox.backend.common.typ.Tuple[Tangent, dict]