newton_cg#

t3toolbox.optimizers.newton_cg(geometry, kind, sample, data, x0, order=None, weight=None, verbose=False, val_sample=None, val_data=None, callback=None, use_jit=False, regularizer=None, chunk_size='auto', g0_reference=None, g0norm_newton=None, g0norm_cg=None, cg_forcing_power=0.5, 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, *, 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(
        geometry,                   # ragged/uniform MANIFOLD (intended) / COREWISE (must match x0)
        kind:                   str,      # 'apply' / 'entries' / 'probe' (+ '_derivatives')
        sample:                 typ.Any,  # ww / index, or (ww, pp) / (index, pp) for derivatives
        data:                   typ.Any,  # observed values to fit
        x0:                     Point,    # initial point (zero is fine on the manifold)

        order:                  typ.Optional[int] = None,      # derivative kinds: highest order (required)
        weight:                 typ.Optional[typ.Any] = None,  # residual weight ω: per-mode (probe) / ω[mode,order] (derivatives)

        verbose:                bool = False,    # print per-iteration diagnostics (a relative-error table + more)
        val_sample:             typ.Any = None,  # optional validation sample (same layout as `sample`) -> a train|val table
        val_data:               typ.Any = None,  # optional validation data (both given adds the val column)

        callback:               typ.Optional[typ.Callable] = None,  # custom callback(NewtonInfo) each iter (overrides `verbose`)

        use_jit:                bool = False,      # jit the inner CG: auto-converts x0/sample/data to jax -> a jax-backed float32 result; warns + runs eager if jax absent
        regularizer:            typ.Any = None,    # optional regularizer, e.g. optimizers.IdentityRegularizer(λ)
        chunk_size:             typ.Any = 'auto',  # probe_derivatives 𝒥ᵀ memory chunk; 'auto' -> estimate_chunk_size (docs/chunking.md)

        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 is given
        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
        max_newton:             int   = 30,    # Newton-iteration cap (rejected trust-region trials included)
        gtol_rel:               float = 1e-8,  # stop when ‖g‖ <= gtol_rel * ‖g0‖
        cg_maxiter:             int   = 200,   # inner CG iteration cap per Newton step
        c_armijo:               float = 1e-4,  # Armijo sufficient-decrease constant (line search only)
        on_line_search_failure: str = 'stop',  # Armijo exhausted: 'stop' = reject the step and terminate; 'accept' = take the last trial

        hessian:                str = 'gauss_newton',        # or 'exact' | 'switch' (GN, then exact); case-insensitive
        curvature_damping:      typ.Optional[float] = None,  # exact, switch: lift damping, relative to ‖X‖; None = the default
        step_control:           typ.Optional[str]   = None,  # None = 'line_search' (GN) / 'trust_region' (exact, switch)
        tr_radius0:             typ.Optional[float] = None,  # trust region only: Δ0 > 0; None = the GN Cauchy length
        *,
        start_frame:                typ.Optional[typ.Union['bvf.T3Frame', 'ubv.UT3Frame']] = None,   # a frame of x0 (after its reduction) for iteration 0
        padded_from:                typ.Optional[Point] = None,   # the old point; rank 0 = the zero tensor

        padded_oversampling:        typ.Optional[int]   = None,   # None = 5; padded_from only
        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
        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,                 # True: stats['timing'], the seconds by phase (changes no number)

        switch_tau:                 typ.Optional[float] = None,   # None = 0.25; in [0, 1); 0 = never switch; 'switch' only
        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'; or 'all': the rows that track
) -> typ.Tuple[Point, dict]:

Inexact Riemannian Newton-CG with a line search or a trust region – the manifold workhorse. Ragged or uniform x0 (see gradient_descent()). See t3toolbox.backend.optimizers.newton_cg().

hessian picks the local model’s Hessian: 'gauss_newton' (the default) or 'exact', the exact Riemannian Hessian – the Gauss-Newton term plus the curvature term the Gauss-Newton model drops, which gives the superlinear Newton tail on a nonzero-residual fit (q-quadratic with cg_forcing_power=1.0) at a few times the cost of a Gauss-Newton Hessian-apply. Its default step control is a trust region (step_control='trust_region': Steihaug-Toint CG, one trial retraction per step, accepted on the model’s predicted decrease), the Gauss-Newton one the Armijo line search; either combines with either. 'switch' starts with Gauss-Newton and switches to the exact Hessian inside the run, once the exact model predicts the objective clearly better (below; its default step control is the trust region too). tr_radius0 is the initial trust radius and curvature_damping the exact Hessian’s lift damping (relative to ‖X‖; None = the geometry’s default); each raises where it would have no effect. The exact Hessian is implemented for every sampling kind, on every geometry (MANIFOLD / COREWISE, their uniform twins, and the shared wrappers of all four). hessian also sizes chunk_size='auto' (least_squares_problem()). Details, stop reasons and the trust-region rules: the backend t3toolbox.backend.optimizers.newton_cg().

Both stopping tests are relative to a reference ‖g0‖. By default (g0_reference=None) a manifold geometry uses the gradient norm at the zero tensor of x0’s ranks – the right scale after a warm start, whose own initial gradient is deflated – and a corewise geometry the warm-start ‖g(x0)‖; g0_reference='warm_start' keeps the 2026.2.0 behaviour. The explicit overrides g0norm_newton / g0norm_cg win, and cg_forcing_power trades more CG iterations per Newton step for fewer Newton steps (all detailed on the backend; docs/fitting_and_optimization.md §5).

The solver options – max_newton, gtol_rel, cg_maxiter, c_armijo, on_line_search_failure, the references above, cg_forcing_power, hessian, curvature_damping, step_control and tr_radius0 – are the backend’s, with the backend’s defaults, passed straight through. They are explicit keywords (there is no **kwargs pass-through), so a misspelt option raises TypeError at the call, before the problem is built. The switch_* options (below) are the backend’s too, checked at the call before the problem is built and forwarded only when set.

verbose=True prints a per-iteration diagnostic block (objective / gradient, CG stats, line search, and the per-(mode, order) relative-error table); pass val_sample / val_data to add a validation column. With a regularizer attached the objective is shown split as obj = misfit + reg (the ½‖ω⊙r‖² data misfit vs ρ(x)); both parts are on every record as misfit / regularization (the latter None when unregularized), in stats['history'] (always) and stats['diagnostics'] (when verbose). This is a thin convenience over the backend display – a raw-.data user builds the same callback with t3toolbox.backend.optimizer_display.make_newton_display() and passes it as callback= to t3toolbox.backend.optimizers.newton_cg(). A custom callback overrides verbose. Works on both the ragged and uniform layers (the uniform block_sumsq reduces the packed residual directly; validation data is packed automatically).

After a rank increase (padded_from / start_frame / g0_reference='cone'). Rank continuation restarts Newton from x0 = the previous level’s x_old zero-padded to the new ranks. The orthonormal frame of such a point is arbitrary on the new slots, so the first Gauss-Newton step can miss the directions the fit needs. padded_from=x_old builds iteration 0’s frame by aligning the new slots with the misfit gradient (t3toolbox.backend.optimizers.padded_start(); the padded_* options: padded_max_passes=0 is the hint-free padded frame). x_old must be x0’s layer, shape, stack and padded N; it is reduced to minimal ranks first, and a structurally zero x_old (any Tucker or interior TT rank 0) is the zero tensor. In safe mode x0 must equal x_old (the zero padding) and, with sharing, x_old’s factors must be tied. start_frame gives the frame directly (a T3Frame / UT3Frame of x0 after its reduction; checked structurally, and in safe mode orthonormal and representing x0). g0_reference='cone' takes the reference ‖g0‖ at the zero tensor at the frame aligned with the data gradient there (the cone_* options; cone_max_passes=0 evaluates it at the zero tensor’s hint-free start). use_jit governs the alignment as well as CG. These need a manifold geometry. Every set option is forwarded and unset ones are not, so without these keywords the run and its stats are exactly as before; with them stats gains 'start_frame', 'start_movements' and 'cone_movements'.

>>> import numpy as np
>>> import t3toolbox.tucker_tensor_train as t3
>>> import t3toolbox.manifold as t3m
>>> import t3toolbox.optimizers as optimizers
>>> np.random.seed(0)
>>> shape = (5, 6, 5)
>>> ww = [np.random.randn(80, n) for n in shape]
>>> data = t3.TuckerTensorTrain.randn(shape, (3, 4, 3), (1, 3, 3, 1)).probe(ww)
>>> x_old, _ = optimizers.newton_cg(t3m.MANIFOLD, 'probe', ww, data,
...                                 t3.TuckerTensorTrain.randn(shape, (2, 2, 2), (1, 2, 2, 1)), max_newton=5)
>>> x0 = x_old.resize(shape, (3, 4, 3), (1, 3, 3, 1))                  # the next level, zero-padded
>>> x, stats = optimizers.newton_cg(t3m.MANIFOLD, 'probe', ww, data, x0, max_newton=5, padded_from=x_old)
>>> stats['start_frame'], len(stats['start_movements']) <= 10
('padded', True)

Switching from Gauss-Newton to the exact Hessian (hessian='switch'). Gauss-Newton converges linearly on a nonzero-residual fit, at a rate set by the curvature term it drops; the exact Hessian gives the superlinear tail but costs a few Gauss-Newton Hessian-applies per apply and is indefinite far from a minimizer. 'switch' makes the choice inside one call: it starts with Gauss-Newton, measures after each step whether the exact model would have predicted the actual change of the objective better, and switches to the exact Hessian for good once it clearly would have. With s the step taken (αp on the line search, p in the trust region), Δf the objective’s actual change, m_GN(s) the Gauss-Newton model’s predicted change (α·slope + ½α²·pHp in the row’s fields) and ⟨s, K s⟩ the curvature term (the exact Hessian’s quadratic form minus Gauss-Newton’s; t3toolbox.backend.optimizers.newton_cg() has it in full):

m_N(s) = m_GN(s) + ½⟨s, K s⟩                      the exact model's predicted change: one curvature product
e_GN   = |Δf − m_GN(s)|,   e_N = |Δf − m_N(s)|    how far each model missed
hit    : e_N < switch_tau · e_GN                  on a countable step (below)
switch : switch_k consecutive hits                for good, from the next point on

With the defaults (switch_tau=0.25, switch_k=2): the exact model must have predicted the objective at least four times better than Gauss-Newton, on two clean steps in a row. Near a minimizer e_GN is the dropped curvature term, second order in the step, while e_N is third order, so e_N / e_GN falls toward 0; in the transient far from it the ratio is about 1 or more, so a threshold well below 1, required twice running, rarely fires early.

What counts, what resets. A step is countable iff the full model step was taken: an accepted trust-region trial, or an Armijo step with α = 1. Everything else resets the count to 0: a miss, a rejected trust-region trial, a line-search backtrack, the −g fallback (CG’s step was not a descent direction), a step forced by on_line_search_failure='accept', and a step whose two errors are both at the objective’s rounding level. A CG step stopped on the trust region’s boundary, truncated or at its iteration cap counts like any other (both models are evaluated at the step actually taken). The rounding gate: Δf is a difference of two objective values, so below 1000·ε·(‖ω⊙y‖·‖ω⊙r‖ + |f|) (ε the residual dtype’s machine epsilon: the trust region’s objective_floor scale times 100) neither error can be measured. In jax’s default float32 (use_jit=True without x64) only large early steps clear it and the switch rarely fires: enable jax x64 with 'switch'.

The options, each with hessian='switch' only (elsewhere a structural error):

  • switch_tau (None = 0.25; in [0, 1)) – the hit threshold. 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 (None = 2; an int >= 0) – the consecutive hits that switch. 0 is exact from iteration 0: the exact run with cg_forcing_power=switch_cg_forcing_power.

  • switch_cg_forcing_power (None = 1.0) – the CG forcing power from the switch on (1.0 gives the exact Hessian’s q-quadratic tail); cg_forcing_power (default 0.5) stays the Gauss-Newton phase’s.

  • switch_track (None = 'countable'; or 'all', case-insensitive) – the steps the curvature product runs on: the countable ones (any other step resets the count whatever e_N is), or every Gauss-Newton-phase step, which reports e_N there too, at one product each, and switches at the same row.

An option the run would not read raises too: switch_tau or switch_track with switch_k=0 (nothing is tracked), switch_k or switch_cg_forcing_power with switch_tau=0 (nothing switches). The default step control is the trust region, whose radius carries across the switch; the line search works too. curvature_damping applies to every exact build, the tracking ones included. Each call starts in Gauss-Newton with a count of 0 – nothing carries across calls, so each level of a rank continuation decides afresh (after a rank increase the run may have left the basin). The switch may never fire, at no cost beyond the tracking: 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; at a zero-padded start).

What it costs. Each Gauss-Newton-phase point 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; each tracked step adds one curvature product, about two or three Gauss-Newton Hessian-applies. Under use_jit CG compiles at most two programs per call: the Gauss-Newton one (which a Gauss-Newton run at the same structure has already compiled) and the exact one.

What it reports. Each history row’s hessian is the model that solved its step ('gauss_newton' before the switch, 'exact' from it on), and every row of a switch run carries five more fields (t3toolbox.backend.optimizers.NewtonInfo): switch_e_gn (each Gauss-Newton-phase step), switch_pKp and switch_e_n (each tracked step: the curvature product ⟨p, K p⟩ and e_N), switch_count (the count after the row, in the Gauss-Newton phase) and switch_fired (True on the row whose count reached switch_k). stats gains 'hessian' ('switch'), 'switch_track' (the resolved value; None with switch_k=0) and '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). With verbose=True each Gauss-Newton-phase step row’s header carries sw and the ratio e_N / e_GN (— where no product ran), then × the count, the switching row adds ⇒ exact (all before a last row’s stop reason), and the exact rows after it show their κ σ ε cells:

iter  1 | obj 2.537e+05 ... | Δf -2.03e+02 ρ 0.85 | 0.03s | sw 3.0e-03 ×2 ⇒ exact
iter  2 | obj 2.535e+05 ... | Δf -9.75e+01 ρ 1.00 | 0.05s | κ -3.5e-01 σ 5.8e+01 ε 1.3e-04

The rule, the options, the cost, when to use it and a worked run: Fitting & optimization §4.14.

Timing a run (timing=True). Where does a Newton run’s time go – CG or the model build, the retraction or the line search’s extra trials, the alignment of a padded start, the compiler? timing=True splits each history row’s wall_time window into phases and adds stats['timing']. It changes no number: x and every other stats field are bitwise the untimed run’s, the wall_time clock readings aside. A row’s phases, in the order the time line shows them (None when one did not run on that row; t3toolbox.backend.optimizers.PhaseSeconds):

  • frame, sweep, companion, residual, curvature – the local model’s build: the orthonormal frame at the point, the sampling kind’s sweep at it, the geometry’s per-frame data, the residual, and with hessian='exact' or 'switch' the curvature data. None on a row that reuses the model (after a rejected trust-region trial).

  • gradient – the misfit transpose Π 𝒥ᵀ r (in every mode) and what reads it: the objective’s parts, the gradient and its norm.

  • reference – row 0 only: the reference ‖g0‖ of g0_reference, the 'cone' alignment included.

  • cg – the CG solve (under use_jit, one compiled call). forms – the step’s scalars (the slope, pᵀHp, ‖p‖, the first trust radius).

  • trial_retraction, trial_objective – every trial’s retraction and objective (trials counts them).

  • tracking – hessian='switch': a tracked Gauss-Newton-phase row’s curvature product (switch_pKp); None on every other row.

  • previous_callback – the previous row’s callback (a display) and bookkeeping, so a heavy display appears a row late; remainder – what no phase covers.

stats['timing'] carries the run’s total, its one-offs (setup; alignment and alignment_passes with padded_from; reference_passes with 'cone'; last_callback), each phase summed over the rows (phases), the compile wait likewise (compile), CG’s seconds per iteration (cg_per_iteration) and every row’s record (rows). total is the setup, the alignment, the rows’ windows and the last callback, end to end. With verbose=True each row also prints a time line, and the run ends with a closing table; a custom callback reads the row’s record as NewtonInfo.timing.

What it costs. Every phase ends by waiting for its results, because jax dispatches asynchronously: without the wait, one phase’s work would be charged to whichever later phase first needed it. On numpy the waits are free. On jax they serialize the run (the host no longer queues the next phase while the device works), so a timed jax run is slower, and its times describe the serialized run. On the maintainer’s laptop CPU, timing on against off differed by -4 % to +2 % on numpy, eager jax and use_jit, ragged and uniform, at d = 3 and d = 6: within the run-to-run noise. On an A100 GPU the same cases and a downstream level differed by -1.4 % to +3.1 %, also within the noise.

The compile column. On a jax run each phase also carries jax’s compile wait (compile_seconds: tracing, lowering and backend compilation, from jax.monitoring). With use_jit=True CG is one program, compiled on its first call (row 0’s cg), and a second run at the same structure compiles nothing; the eager phases around CG compile their operations the first time they run, and the uniform alignment’s whole-loop program is compiled inside alignment. Eager jax compiles every operation of a new structure on first use. On the laptop, the example below run on jax (x64) took 36 s cold under use_jit, 31 s of it compiling (16 s in the alignment, 2.9 s CG’s program), and 3.5 s at the same structure again; eager, 71 s cold (54 s compiling) and 14 s again. The column is None on numpy and on a jax whose jax.monitoring cannot unregister a listener (jax 0.4.30). The listener is process-global: compiles in other threads, or in a timed run inside a callback, are counted too.

What is not timed. This function’s own setup – building the problem, reducing x0 and padded_from to minimal ranks, building the display – runs before the backend’s clock starts, so stats['timing'] describes the backend call, the same for a raw-.data user. The phases, the costs and the display in full: Fitting & optimization §4.13.

For a large-|W| uniform probe_derivatives fit, chunk_size='auto' (the default) sizes the 𝒥ᵀ gradient assembly’s memory automatically (via estimate_chunk_size()); pass an int / None to override. Other kinds and the ragged layer ignore it. See Memory chunking of the derivative transpose (chunk_size).

Examples

Recover a low-rank tensor from noiseless apply measurements on the uniform layer – a uniform x0 (with UNIFORM_MANIFOLD) returns a UniformTuckerTensorTrain (a zero start is fine on the manifold; unit-norm probe rows keep the least-squares well-conditioned):

>>> import numpy as np
>>> import t3toolbox.tucker_tensor_train as t3
>>> import t3toolbox.uniform_tucker_tensor_train as ut3
>>> import t3toolbox.uniform_manifold as ut3m
>>> import t3toolbox.optimizers as optimizers
>>> np.random.seed(0)
>>> A = t3.TuckerTensorTrain.randn((6, 7, 8), (2, 2, 2), (1, 2, 2, 1))
>>> ww = [np.random.randn(120, N) for N in (6, 7, 8)]
>>> ww = [w / np.linalg.norm(w, axis=1, keepdims=True) for w in ww]   # unit-norm rows
>>> b = A.apply(ww)
>>> x0 = ut3.UniformTuckerTensorTrain.from_t3(t3.TuckerTensorTrain.zeros((6, 7, 8), (2, 2, 2), (1, 2, 2, 1)))
>>> x_opt, stats = optimizers.newton_cg(ut3m.UNIFORM_MANIFOLD, 'apply', ww, b, x0, max_newton=30)
>>> type(x_opt).__name__                              # returned in the same (uniform) representation
'UniformTuckerTensorTrain'
>>> bool(np.linalg.norm(x_opt.to_dense() - A.to_dense()) / np.linalg.norm(A.to_dense()) < 1e-6)
True

For a ragged fit pass t3m.MANIFOLD and a TuckerTensorTrain x0 instead; the call is otherwise identical.

The exact Hessian. On a noisy probe_derivatives fit warm-started near the solution, the exact Hessian (with its default trust region, and cg_forcing_power=1.0 for the q-quadratic tail) converges in a fraction of the steps Gauss-Newton takes (Gauss-Newton is linear there, about halving ‖g‖ per step; where its tail ends – the gradient test or a failed line search – depends on the BLAS’s rounding):

>>> import t3toolbox.manifold as t3m
>>> 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))
>>> target = t3.TuckerTensorTrain.randn(shape, (3, 3, 3), (1, 3, 3, 1))
>>> data = [z + 0.01 * rng.standard_normal(z.shape) for z in target.probe_derivatives(ww, pp, 1)]
>>> x0, _ = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data,
...                              t3.TuckerTensorTrain.randn(shape, (2, 2, 2), (1, 2, 2, 1)), order=1,
...                              max_newton=5)
>>> opts = dict(order=1, max_newton=40, g0_reference='warm_start')
>>> _, gn = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data, x0, **opts)
>>> _, ex = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data, x0, hessian='exact',
...                              cg_forcing_power=1.0, **opts)
>>> ex['history'][0]['step_control'], ex['stop_reason'] in ('gradient', 'objective_floor')
('trust_region', True)
>>> gn['newton_steps'] > 2 * ex['newton_steps']
True

Switching from Gauss-Newton to the exact Hessian. The same problem with hessian='switch': Gauss-Newton steps until the exact model has twice running predicted the objective four times better, then the exact Hessian, in a fraction of Gauss-Newton’s steps:

>>> _, sw = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data, x0, hessian='switch', **opts)
>>> sw['hessian'], sw['switch_track'], sw['stop_reason'] in ('gradient', 'objective_floor')
('switch', 'countable', True)
>>> j = sw['switched_at']                                   # the first row whose model is exact
>>> fired = sw['history'][j - 1]                            # the row that switched
>>> [row['hessian'] for row in sw['history'][j - 1:j + 1]], fired['switch_fired'], fired['switch_count']
(['gauss_newton', 'exact'], True, 2)
>>> fired['switch_e_n'] < 0.25 * fired['switch_e_gn']
True
>>> sw['newton_steps'] < gn['newton_steps'] / 2             # gn: Gauss-Newton with its line search
True

Timing a run. The same problem one level up: the rank-2 fit x0 zero-padded to rank 3, restarted from the aligned frame (padded_from) with the 'cone' reference. timing=True adds stats['timing']; the phases tile each row’s window, and the run is the untimed run:

>>> x_new = x0.resize(shape, (3, 3, 3), (1, 3, 3, 1))                      # the next level, zero-padded
>>> level = dict(order=1, max_newton=40, hessian='exact', cg_forcing_power=1.0, padded_from=x0,
...              g0_reference='cone')
>>> _, timed = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data, x_new, timing=True,
...                                 **level)
>>> T = timed['timing']
>>> rows = T['rows']                                                        # one record per history row
>>> len(rows) == len(timed['history'])
True
>>> all(abs(sum(s for s in row['seconds'].values() if s is not None) - row['window']) < 1e-9
...     for row in rows)                                                     # the phases tile each window
True
>>> rows[0]['seconds']['reference'] is not None, rows[1]['seconds']['reference']     # row 0 only
(True, None)
>>> T['compile'] is None, len(T['alignment_passes']) == len(timed['start_movements'])   # numpy: no compiler
(True, True)
>>> _, plain = optimizers.newton_cg(t3m.MANIFOLD, 'probe_derivatives', (ww, pp), data, x_new, **level)
>>> 'timing' in plain, plain['losses'] == timed['losses']                   # the same run, untimed
(False, True)

Precision — jit runs in jax’s default float32. use_jit=True opts into jax world, whose default dtype is float32. Fit a small exact-rank tensor three ways; the giveaway throughout is the returned core’s dtype. First set up the problem:

>>> import t3toolbox.manifold as t3m
>>> np.random.seed(0)
>>> A = t3.TuckerTensorTrain.randn((4, 5, 6), (2, 2, 2), (1, 2, 2, 1))
>>> ww = [np.random.randn(60, N) for N in (4, 5, 6)]
>>> ww = [w / np.linalg.norm(w, axis=1, keepdims=True) for w in ww]
>>> b = A.probe(ww)
>>> x0 = t3.TuckerTensorTrain.zeros((4, 5, 6), (2, 2, 2), (1, 2, 2, 1))
>>> def rel_err(x): return float(np.linalg.norm(np.asarray(x.to_dense()) - A.to_dense()) / np.linalg.norm(A.to_dense()))
  1. The numpy path is float64 and recovers to near machine precision (~1e-10):

>>> x_np, _ = optimizers.newton_cg(t3m.MANIFOLD, 'probe', ww, b, x0, max_newton=20)
>>> str(x_np.data[0][0].dtype), bool(rel_err(x_np) < 1e-8)
('float64', True)
  1. use_jit=True runs the SAME code in jax’s default float32 and stalls ~1000x coarser (~1e-7):

>>> x_jit, _ = optimizers.newton_cg(t3m.MANIFOLD, 'probe', ww, b, x0, max_newton=20, use_jit=True)
>>> str(x_jit.data[0][0].dtype), bool(rel_err(x_jit) > 1e-8)
('float32', True)

(3) Enabling jax x64 restores float64 under jit – full accuracy again (~1e-10). jax_enable_x64 is a global, process-wide flag, so restore it right after the fit; the check reads values captured while it was on:

>>> import jax
>>> jax.config.update("jax_enable_x64", True)
>>> x_x64, _ = optimizers.newton_cg(t3m.MANIFOLD, 'probe', ww, b, x0, max_newton=20, use_jit=True)
>>> dtype_x64, ok_x64 = str(x_x64.data[0][0].dtype), bool(rel_err(x_x64) < 1e-8)
>>> jax.config.update("jax_enable_x64", False)          # restore the default before asserting (no leak)
>>> dtype_x64, ok_x64
('float64', True)
Parameters:
  • kind (str)

  • sample (Any)

  • data (Any)

  • x0 (Point)

  • order (Optional[int])

  • weight (Optional[Any])

  • verbose (bool)

  • val_sample (Any)

  • val_data (Any)

  • callback (Optional[Callable])

  • use_jit (bool)

  • regularizer (Any)

  • chunk_size (Any)

  • g0_reference (Optional[str])

  • g0norm_newton (Optional[float])

  • g0norm_cg (Optional[float])

  • cg_forcing_power (float)

  • max_newton (int)

  • gtol_rel (float)

  • cg_maxiter (int)

  • c_armijo (float)

  • on_line_search_failure (str)

  • hessian (str)

  • curvature_damping (Optional[float])

  • step_control (Optional[str])

  • tr_radius0 (Optional[float])

  • start_frame (Optional[Union[T3Frame, UT3Frame]])

  • padded_from (Optional[Point])

  • padded_oversampling (Optional[int])

  • padded_oversampled_passes (Optional[int])

  • padded_max_passes (Optional[int])

  • padded_tol (Optional[float])

  • padded_alternate (Optional[bool])

  • padded_seed (Optional[int])

  • cone_oversampling (Optional[int])

  • cone_oversampled_passes (Optional[int])

  • cone_max_passes (Optional[int])

  • cone_tol (Optional[float])

  • cone_alternate (Optional[bool])

  • cone_seed (Optional[int])

  • timing (bool)

  • switch_tau (Optional[float])

  • switch_k (Optional[int])

  • switch_cg_forcing_power (Optional[float])

  • switch_track (Optional[str])

Return type:

Tuple[Point, dict]