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 = −gby (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_jitjits 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 ause_jit=Truecall 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 gaugedHis positive-definite on the manifold, and CG truncates on the gauge-singular corewiseH.'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 implementingcorewise_hessianand 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 withcg_forcing_power=1.0, order about 1.5 at the default0.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‖,Nonefor 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)|withm_N(s) = m_GN(s) + ½α²⟨s, Π Lᵀ K_N L Π s⟩(one curvature product). A countable row withe_N < switch_tau·e_GN(default0.25) is a hit;switch_k(default2) 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−gfallback 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_poweris the Gauss-Newton phase’s forcing power andswitch_cg_forcing_power(default1.0) the exact phase’s.switch_tau=0tracks and never switches (the run is the Gauss-Newton run with the same step control, bit for bit, plus the tracking);switch_k=0is exact from iteration 0 (the exact run withcg_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 atd = 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 theswitch_*fields (NewtonInfo);statsgains three keys (below). Aswitch_*option withouthessian='switch'raises, as does one the run would not read (switch_tauorswitch_trackwithswitch_k=0;switch_korswitch_cg_forcing_powerwithswitch_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 alongretract(α p).'trust_region'(the exact and switch default – the exactHis 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 trialretract(p), accepted iff the ratio of the actual to the model’s predicted changeρ = Δf / (gᵀp + ½ pᵀHp)exceeds0.1.Δ ← ¼‖p‖whenρ < 0.25(or not finite);Δ ← min(2Δ, 10⁴Δ0)whenρ > 0.75on a boundary step.Δ0 = tr_radius0, by default the Gauss-Newton Cauchy length‖g‖³ / ⟨g, H_GN g⟩. A rejected trial keepsx– and the local model, which is rebuilt only after an accepted step – emits its own history row (tr_accepted=False) and counts towardmax_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 (convergedstaysFalsebecause the gradient test did not fire); else'trust_region_floor'whenΔhas fallen below10⁻¹²·Δ0.tr_radius0with'line_search'raises, as doeson_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 azero_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 raisesValueError.'warm_start'– the initial gradient norm‖g(x0)‖(the 2026.2.0 default;1.0if 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; thecone_*options,use_jitas below).'zero'evaluates it at a fixed, data-independent frame, which can miss most of the gradient;cone_max_passes=0evaluates 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 atgeom.frame(x0)by default.start_framegives a frame ofx0instead (structurally checked by the geometry’srequire_frame_structure);padded_from=x_oldbuilds it:x0isx_oldzero-padded to the target ranks, whose own frame is arbitrary on the new slots, andpadded_start()aligns the new slots with the misfit gradient (thepadded_*options;padded_max_passes=0is the hint-free padded frame). Both need a manifold geometry.use_jitgoverns the alignment as well as CG. With either keyword,stats['start_frame']is'given'or'padded'andstats['start_movements']the passes. An option of a group set without its group engaged (padded_*withoutpadded_from,cone_*without'cone'or withg0norm_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'raisesValueError. The explicit overrides then win, with a chained fallback:g0norm_newtonsets the Newton reference (and CG inherits it unlessg0norm_cgis also given – so withg0norm_newtongiven the zero reference is not computed at all);g0norm_cgalone sets only the CG reference. A non-positive override raisesValueError. Every history row records the kinds (g0_reference,cg_reference;'override'for an explicit value).cg_forcing_power(default0.5, the conventional Eisenstat-Walker value, in both modes) tunes CG effort per Newton step: since‖g‖/‖g0‖ < 1near 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, and1.0is what makes the exact Hessian’s tail q-quadratic. Themin(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’sNewtonInforow carriesls_failed=Trueandalphais the step of the last trial actually evaluated (2^-39), sodelta_f/rho/step_reldescribe a step that was genuinely tried.callback, if given, is called with aNewtonInfoeach 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 withuse_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().statsis{'losses', 'newton_steps', 'newton_accepted', 'stop_reason', 'history'}:newton_stepscounts the CG solves (the history rows that took a step),newton_acceptedthe steps taken (newton_stepsminus the rejections: an Armijo-exhausted one under'stop', or the rejected trust-region trials),stop_reasonis'gradient'/'max_newton'/'line_search'/'objective_floor'/'trust_region_floor'(seeNewtonInfo), andhistoryis one_newton_scalar_record()per iteration (losses[k] == history[k]['objective']). (The 2026.2.0stats['newton']is removed; it isnewton_steps.)hessian='switch'addsstats['hessian'] = 'switch',stats['switch_track']('countable'or'all';Nonewithswitch_k=0) andstats['switched_at'], the index of the first row whose model is exact (len(history)when the switch fired on the last row;0withswitch_k=0;Noneif it never fired).timing=Trueaddsstats['timing'](below).Timing (
timing=True; it changes no number). Each row’swall_timewindow is split by phase intoNewtonInfo.timing(aNewtonTiming;PhaseSecondslists the phases), with jax’s compile wait per phase on a jax run (Noneon numpy, and on a jax whosejax.monitoringcannot 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, withsetup,alignmentandlast_callback;Noneas above),cg_per_iteration(CG’s seconds less its compile wait, per CG iteration) androws(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-gbefore 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. AProblemsubclass that overrideslocal_modelis called as without timing, and its whole build is reported inframe. The geometry memberaligned_padded_frameis asked for its seconds per pass only when its signature namestiming(seeGeometry). Withmake_newton_display()as the callback, each row prints atimeline and the run ends with a closing table. What each phase covers, what the synchronization costs and how the compile column reads underuse_jitand 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]