Optimizers API

The optimizer, its problem, state, cache and result, the training step, and the observers.

GeometricOptimizers.OptimizerSolution — Type
OptimizerSolution

A type alias for the solution of an optimizer: an AbstractVector, a Manifold, or a NeuralNetworkParameters.NetworkParameters holding a whole set of network parameters.

A set of parameters enters this package as a container and never as a bare NamedTuple. That is the constraint every other alias in this file is written against, so it is worth saying why the obvious alternative is not available.

A parameter set has to be a type somebody owns. NamedTuple{S,<:Tuple{Vararg{AbstractArray{T}}}} picks out the same values, but it is an alias for Base.NamedTuple rather than a type of its own, and three things follow:

  • a method taking one is a method on Base.NamedTuple. Unless the function is also this package's, that is type piracy — and it is global, changing what the function means for every keyed NamedTuple in any session that loads this package, directly or through a dependency;
  • it cannot be told apart from any other NamedTuple alias in the same method table. It would overlap GlobalSectionNamedTuple and the bare NamedTuple that a nested section tree is written on, and on the overlap neither method of such a pair is more specific — an ambiguity rather than a choice. optimizers/named_tuple_wrapper.jl is where that would bite;
  • its T binds through a Vararg bound on the values, which asserts "flat, and every leaf an AbstractArray{T}". NetworkParameters{T} asserts something else: one element type over leaves at any depth. A union of the two would say one thing about one argument shape and another about the other.

NetworkParameters{T} has none of those properties. It also binds T from a direct type parameter rather than through a Vararg bound on value types, which makes it the cheapest member of this union to intersect.

A caller holding a bare `NamedTuple` wraps it

NetworkParameters(ps) shares the leaf arrays rather than copying them, so an in-place solve still writes through to the caller's own arrays and nothing has to be copied back. That is what GeometricMachineLearning and GMLDatasets do at the boundary.

source
GeometricOptimizers.OptimizerState — Type

An OptimizerState is a data structure for the dispatch on different algorithms.

It needs to implement three methods,

initialize!(alg::OptimizerState, ::AbstractVector)
update!(alg::OptimizerState, ::AbstractVector)
solver_step!(::AbstractVector, alg::OptimizerState)

that initialize and update the state of the algorithm and perform an actual optimization step.

Further the following convenience methods should be implemented,

problem(alg::OptimizerState)
gradient(alg::OptimizerState)
hessian(alg::OptimizerState)
linesearch(alg::OptimizerState)

which return the problem to optimize, its gradient and (approximate) Hessian as well as the linesearch algorithm used in conjunction with the optimization algorithm if any.

See NewtonState for a struct that was derived from OptimizerState.

Info

Note that a OptimizerState is not necessarily a NewtonState as we can also have other optimizers, Adam for example.

source
GeometricOptimizers.latest_gradient — Method
latest_gradient(cache)

The array holding the most recently evaluated gradient: a line search trial point while linesearch_problem's $\varphi'$ is being evaluated, and the accepted iterate once solver_step! has called refresh_latest_gradient! on it.

OptimizerStatus reports the Riemannian norm of this gradient as rg, through latest_gradient_norm; see there for why that is not the norm of this array. The array is deliberately not gradient: the latter is $\nabla{}f(x_k)$ at the iterate the step is built from, which the direction and the state updates need to keep reading unchanged.

Implementation

Every cache in this package carries a scratch array of its own for this, the field g̃, and a flag g̃_is_current for the pairing store_gradient! relies on. The defaults of this method and of the three that go with it (refresh_latest_gradient!, latest_gradient_is_current, invalidate_latest_gradient!) read those two fields; see GradientCache for why g̃ may not be shared with gradient.

source
GeometricOptimizers.latest_gradient_norm — Method
latest_gradient_norm(cache)

The Riemannian norm $\sqrt{g_x(\Delta, \Delta)}$ of the gradient $\Delta$ at the iterate cache holds, as refresh_latest_gradient! last stored it: the Euclidean norm on a vector, the norm of metric on a Manifold, and the two combined in quadrature over the leaves of a parameter set. OptimizerStatus reports it as rg, and the gradient stop reads it.

It is the same number for every method. latest_gradient holds the gradient in the form the method takes it, see GeometricOptimizers.gradient_rep!, and on a SymplecticStiefelManifold those forms have different norms, so a norm of that array would stop each method at a different point. On a vector, a StiefelManifold and a GrassmannManifold every form is global_rep of $\Delta$, whose norm over its free parameters is the Riemannian one.

source
GeometricOptimizers.refresh_latest_gradient! — Method
refresh_latest_gradient!(cache, gradient_instance, method)

Evaluate the gradient at the iterate cache currently holds and store it in latest_gradient, in the form method holds it, and its Riemannian norm in latest_gradient_norm; see GeometricOptimizers.gradient_rep!.

solver_step! calls this once the accepted step has been taken, so that rg is a statement about the point the solve is about to report rather than about the one it started the step from.

It is also what establishes the pairing store_gradient! relies on. See latest_gradient.

source
GeometricOptimizers.store_gradient! — Method
store_gradient!(cache, state, gradient_instance, x, method)

Put the gradient at x in the form method holds it, GeometricOptimizers.gradient_rep!(·, section(state), ∇f(x), method), into gradient_array(cache), which is what the update!(cache, ...) methods build their direction from.

Implementation

This reuses latest_gradient when latest_gradient_is_current says it already holds that value, which in a solve! loop is every iteration but the first: solver_step! refreshes it at the accepted iterate, and the next update! is asked for the gradient at that same iterate in the same frame. The two are not merely close, they are the same values – for the first-order states, update!(state, opt, x) copies section(cache) into the state through advance_state!, so section(state) after it is bit-for-bit section(cache) after solver_step!.

Without the reuse the refresh doubles the gradient evaluations of a first-order step. With the reuse, the refresh is the step's gradient evaluation.

This must run before the cache's `section` and `solution` are overwritten

latest_gradient_is_current compares solution(cache) against x and section(cache) against section(state), so calling it after update!'s _copyto!(section(cache), section(state)) would compare each with itself and report true unconditionally.

source
GeometricOptimizers.EventLog — Type
EventLog(; phases=nothing)

Record optimizer phase notifications as (phase, event) tuples in events.

By default every phase is recorded. Pass a phase name or an iterable of phase names as phases to retain only those phases. Call empty!(log) between runs to reuse an existing log.

Examples

julia> recorder = EventLog();

julia> observe_optimizer_phase(recorder, :gradient) do
           nothing
       end

julia> recorder.events
2-element Vector{Tuple{Symbol, Symbol}}:
 (:gradient, :enter)
 (:gradient, :exit)
source
GeometricOptimizers.NoStepObserver — Type
NoStepObserver()

The default no-op observer used by Optimizer and TrainingOptimizer.

Pass an EventLog, a PhaseTimer, or any callable observer to Optimizer(...; observer=observer) or TrainingOptimizer(...; observer=observer) to receive observer(phase, event) notifications, where event is :enter or :exit and phase is one of :gradient, :objective, or :retraction_application. Notifications are properly nested and an :exit is emitted from a finally block if the observed operation throws.

Callers that need an exclusive optimizer-state timer can bracket solver_step! and the following update! with observe_optimizer_phase(observer, :optimizer_state_direction). A stack-based observer can then pause the outer phase while any nested phase is active. The optimizer itself reports boundaries rather than choosing a clock; PhaseTimer reads the caller-selected clock and can synchronize a CUDA device immediately before each timestamp.

source
GeometricOptimizers.PhaseTimer — Type
PhaseTimer(; phases=nothing, clock=time_ns, synchronize=_no_synchronize)

Accumulate exclusive phase times in nanoseconds.

The exclusive dictionary stores the accumulated time for each phase and calls stores how often that phase was entered. Nested phases are excluded from their parent. By default every phase is recorded; pass a phase name or an iterable of phase names as phases to record less. Unselected nested phases are still excluded from a selected parent's time.

clock defaults to time_ns and must return a monotonically increasing count of nanoseconds that UInt64 accepts exactly. Base.time is therefore not a usable clock: it returns seconds as a Float64 and the conversion throws an InexactError. Differences are taken in UInt64, so a clock that ever goes backwards underflows rather than reporting a negative interval.

synchronize is called immediately before every clock reading and defaults to a no-op; a GPU caller can pass its device synchronization function. Call empty!(timer) between runs to reset its accumulators.

source
GeometricOptimizers.observe_optimizer_phase — Method
observe_optimizer_phase(f, observer, phase)

Run f() between matching observer(phase, :enter) and observer(phase, :exit) notifications. The exit notification is guaranteed even when f throws.

source
GeometricOptimizers.curvature_is_usable — Method
curvature_is_usable(ΔxΔg, Δx, Δg)

Whether the secant pair $(\delta, \gamma)$ satisfies the curvature condition, i.e. whether the quasi-Newton update built from it keeps $Q$ positive definite.

Both the BFGS and the DFP update divide by $\delta^T\gamma$ and preserve positive definiteness of $Q$ only for $\delta^T\gamma > 0$ [37]. A test of !iszero(ΔxΔg) admits both signs and denominators that are zero to within round-off, and a rank-two correction divided by such a denominator makes $Q$ badly conditioned or indefinite.

The threshold is relative: an absolute one cannot tell a round-off pairing on a problem scaled to $10^0$ from a legitimate small pairing on a problem scaled to $10^{-15}$. Its exact value matters much less than its existence: 1e-8 and eps(T) behave identically on everything measured here, because the pairs being rejected are the ones that are non-positive rather than merely small.

Rejecting an update is not free

A skipped update leaves $Q$ where it was, so the next direction is built from staler curvature. DFP with a shrink-only Backtracking can take many more iterations under the guard: its direction is systematically under-scaled (see default_linesearch), and a negative-curvature update can inflate $Q$ in a way that partly compensates. In exchange, the iteration count of DFP with an expanding Backtracking depends much less on the starting point.

source
GeometricOptimizers.ensure_descent! — Method
ensure_descent!(cache, method, config)
ensure_descent!(cache, state, method, config)

Replace the direction stored in cache by the steepest-descent direction if it does not descend.

A (quasi-)Newton step solves $H\delta = -\nabla{}f$ and is a descent direction only where $H$ is positive definite. Where it is not — an indefinite Hessian near a saddle, or a quasi-Newton $Q$ that has lost positive definiteness — $\delta$ points uphill. Since a line search only ever returns a non-negative step, the iteration then walks to the nearest stationary point, which may be a maximum.

F(x) = sum(sin.(x) .^ 2) started from x = ones(3) is the smallest example: $\sin^2$ has second derivative $2\cos(2x) = -0.83$ there, so the Newton direction ascends and the solve converges to $\pi/2$, where F is maximal. With this safeguard it descends to 0.

Descent is tested as $\nabla{}f\cdot\delta < 0$. rhs stores $-\nabla{}f$, so the test is $\mathrm{rhs}\cdot\delta > 0$; a direction that fails it — including a NaN one, for which every comparison is false — is replaced by rhs, which always descends. The substitution is reported at config.verbosity ≥ 2.

The four-argument form is what solver_step! calls. For BFGS and DFP the replacement is $M^{-1}\,\mathrm{rhs}$, the steepest descent of the metric at the section of state, as after restart!(::BFGSState); see GeometricOptimizers._metric_inverse!. It is rhs wherever $M$ is the identity, i.e. on every parameter but a SymplecticStiefelManifold and a BiorthogonalManifold. For every other method it is the three-argument form.

Only the (quasi-)Newton methods are safeguarded

Adam and MomentumMethod build their direction from a moving average, which is allowed not to descend on an individual step — that is what the momentum term is for — so their method, on FirstOrderMethodWithState, leaves the direction as it is.

Why the safeguard is here

A line search returns a non-negative step, so it cannot turn an ascent direction into a descent one. The safeguard has to act on the direction before the search.

Examples

F(x) = sum(sin.(x) .^ 2)
x = ones(3)
algorithm = Newton()
state = OptimizerState(algorithm, x)
optimizer = Optimizer(x, F; algorithm = algorithm, linesearch = Bisection())

solve!(x, state, optimizer)
F(x) < 1e-20

# output

true
source
GeometricOptimizers.linesearch_rejected — Method
linesearch_rejected(status)
linesearch_rejected(status, αmax)

Whether a line search reported that it could not decrease the merit along the direction it was given.

The second form takes the ceiling the caller passed as params.αmax and is what solver_step! uses; see A step the caller forbade is not a failed direction below.

SimpleSolvers.solve returns only the step length, so an outcome of LINESEARCH_FLOOR, LINESEARCH_EXHAUSTED or LINESEARCH_NO_DESCENT looks the same as a successful search. The three mean, in order, that the decrease achieved was no larger than the merit's own round-off resolution, that the budget ran out or the merit could not be bracketed, and that $\varphi'(0) \geq 0$. In none of them does the returned $\alpha$ carry a guarantee, and a solve that takes it can walk uphill.

The outcome comes from SimpleSolvers.solve_with_status, which solver_step! calls in place of solve for this reason. (Plain code and not an @extref: SimpleSolvers documents solve_with_status per method and not as a binding, so its inventory has no entry to link to.)

This is deliberately the outcome and not `φ > φ₀`

A test on the merit — "reject the step only if it made things worse" — is the narrower condition. It stops the divergence described in solver_step!, but it leaves the terminal gradient residual larger on the SVD problem of test/verification/svd_optim.jl. A search that ends on the floor has stopped making progress along this direction, and the cheapest remedy is a different direction.

It applies to every method, including `Adam` and `MomentumMethod`

ensure_descent! exempts those two, because a moving average is allowed not to descend on an individual step. That is a statement about the direction and not about the step. A rejected search returns $\alpha = 1$ untouched, so an exemption here would take the longest step along a direction that does not descend, and multiply $f$ by many orders of magnitude. LINESEARCH_EXHAUSTED does the same, so the test here is the whole of linesearch_rejected and not only the ascent outcome.

The momentum recursion does not change: $p \gets \alpha{}p + \nabla{}f$ is evaluated in update!(::MomentumState, …) from gradient_array(cache) after the step, so the direction of the step does not enter it. Only the step changes.

A step the caller forbade is not a failed direction

This is the αmax form. solver_step! gives the search a params.αmax of its own (see DEFAULT_STEP_CEILING), and a search stopped at that ceiling with the merit still falling is classified by the same round-off rule $\tau$ as any other returned step — so it comes back as LINESEARCH_FLOOR when the fall over the whole admissible range was smaller than $\tau$. That outcome is a claim about the direction, and the one-argument form answers it by throwing $Q$ away and searching again along steepest descent. But the search established only that no step this caller permits decreases the merit measurably: the bound was the caller's own.

So LINESEARCH_FLOOR counts as a rejection only where the step returned is strictly below the ceiling that was passed. Where it is the ceiling, the step is taken. The remedy is here and not upstream, because this package supplies the ceiling and can recognise its own bound without a new field on the status.

LINESEARCH_EXHAUSTED and LINESEARCH_NO_DESCENT are deliberately not exempted. Neither is confusable with a bound step: the first says the budget ran out or the merit could not be bracketed, the second that $\varphi'(0) \geq 0$, and both are true of the direction whatever ceiling was in force. A Euclidean solve passes no ceiling at all, so αmax is Inf there, the exemption is unreachable and the two forms agree.

source
GeometricOptimizers.steepest_descent! — Method
steepest_descent!(cache)
steepest_descent!(cache, state)

Replace the direction stored in cache by $-\nabla{}f$, the one direction that always descends.

Implementation

rhs is $-\nabla{}f$ on the (quasi-)Newton caches, so the default copies it across.

It is not on the three first-order caches, where rhs is an alias for direction itself, so copying would be a silent no-op. GradientCache's direction already is $-\nabla{}f$ and the no-op is correct there; MomentumCache and AdamCache hold a moving average and have to be given the gradient explicitly.

The two-argument form is what solver_step! calls after restart!. For BFGS and DFP it is $Q\,\mathrm{rhs}$ with the $Q = M^{-1}$ that restart! has just set, the steepest descent of the metric; see GeometricOptimizers._metric_inverse!. For every other cache it is the one-argument form.

source
GeometricOptimizers.OptimizerStatus — Type
OptimizerStatus

Contains residuals (relative and absolute) and various convergence properties.

This is also used in OptimizerResult.

Examples

x = ones(3)
state = NewtonState(x)
cache = NewtonOptimizerCache(x)
f = 1.
config = Options()
OptimizerStatus(state, cache, f; config = config)

# output

 * Convergence measures

    |x - x'|               = NaN
    |x - x'|/|x'|          = NaN
    |f(x) - f(x')|         = NaN
    |f(x) - f(x')|/|f(x')| = NaN
    |g(x) - g(x')|         = NaN
    |g(x)|                 = NaN
source
GeometricOptimizers._sumsq_leaves — Method
_sumsq_leaves(f, x)

$\sum_i f(x_i)^2$ over the leaves of x, at whatever depth they are.

The quadrature sum in which l2norm and solution_scale both combine their blocks; the two differ only in f. (l2norm is GeometricBase's function, so it has no docstring here to link to.)

Implementation

NeuralNetworkParameters.foldparameters and not map + sum over one level, because a container is a tree of layers and the quantities to combine are at its leaves — map would hand f a whole layer, for which neither of them has a method. foldparameters recurses on the branches and so reaches a leaf at any depth, and it allocates nothing. Its body is generated at literal indices, so its compile time is linear in the number of children of a branch.

foldparameters and not foldstorage, which is the pairing _dot wants and would be wrong here. foldstorage descends past a leaf into the numbers it stores, and solution_scale(Y::Manifold) on a compact manifold is √size(Y, 2) — a nominal value that has nothing to do with those numbers.

false and not zero(T) for the initial value: there is no T in scope, and false is the strong zero that takes its type from whatever it is added to, so a one-block set adds it to that block's value and stays a T. A set has one element type, so every leaf gives it the same T. zero(parameter_eltype(x)) would put the generated _promote_eltypes body of upstream on this path, once per branch shape, which costs compile time.

f is annotated ::F where {F}, so that the method specialises on it even where it only passes f on: Julia does not specialise on a function argument that it does not see called. The docstring of foldparameters asks this of every caller that hands on an op.

source
GeometricOptimizers.contains_nonfinite — Method
contains_nonfinite(a)

Whether a holds any value that is not finite.

NaN is the last thing a diverging solve produces: it reaches Inf first, and before that every finite magnitude on the way, so this tests isfinite and not isnan.

isfinite does not catch 1e200, so it is not the only guard; see convergence_measures for the one that does.

source
GeometricOptimizers.convergence_measures — Method
convergence_measures(status, config)

Checks if the optimizer converged.

Here status is an OptimizerStatus object and config is an SimpleSolvers.Options object.

Extended help

Which iterate `g_converged` is a statement about

rg is latest_gradient_norm, i.e. $\|\nabla{}f(x_{k+1})\|$ in the Riemannian norm at the iterate the step ended at, for every method, and not at the iterate it started from or at the last point that the line search probed.

The distinction matters for a direction that carries momentum. Under SimpleSolvers.Static a stale rg is harmless, because the direction is a scaled gradient and a vanishing gradient means a vanishing step. Under a line search accurate enough to drive $\nabla{}f(x_{k+1}) \approx 0$ it is not: the momentum term still moves the iterate, and a stale rg fires g_converged one step past the minimiser. The refresh costs one gradient evaluation per iteration.

What `x_converged` is guarded against, and what it is not

$\|x - x'\|/\|x'\|$ measures "the iterate stopped moving" only while $\|x'\|$ is bounded, and a diverging solve is the case where it is not: a large step from an iterate of magnitude $10^{100}$ is a small relative change. Two guards, neither of which invents a tolerance:

  • the denominator is solution_scale and not $\|x'\|$. On a compact manifold the two are the same number — $\|Y\|_F = \sqrt{n}$ exactly — up to the point where the iterate leaves the manifold, and there the constant is the true scale and the measured norm is the divergence.
  • x_converged also requires !f_increased. An iterate that has stopped moving is evidence of convergence only if the objective did not just go up. This is the only guard on Euclidean parameters and on SymplecticStiefelManifold, where nothing bounds $\|x\|$ on the manifold itself.

Not covered: a Euclidean solve that runs away downhill, where $\|x\|$ grows without bound and f decreases at every step, has no scale to be measured against and is reported as converged. A threshold on $\|x\|$ would close it, but no property of the problem supplies one: on a manifold the geometry supplies DEFAULT_STEP_CEILING, and in $\mathbb{R}^n$ nothing does.

The divergences are also stopped at their source — linesearch_rejected and curvature_is_usable for a search that failed, DEFAULT_STEP_CEILING for one that succeeded on a step too long for the manifold — and contains_nonfinite catches the Inf/NaN end of the range.

source
GeometricOptimizers.gradient_difference! — Method
gradient_difference!(cache, state)

Write the gradient difference ∇f(xᵏ) - ∇f(xᵏ⁻¹) into cache.Δg, for OptimizerStatus.

Implementation

This is the difference of the two gradients the cache holds itself, latest_gradient at $x_{k+1}$ and gradient at $x_k$, which is the successive difference the status prints and needs no state.ḡ. It is not the γ of the quasi-Newton secant pair, which is one step behind the rg reported next to it. So the two g rows of a status are about one step; see convergence_measures for which iterate rg belongs to.

source
GeometricOptimizers.isconverged — Method
isconverged(status)

Whether any of the three convergence flags convergence_measures sets is set.

The flags are a disjunction on purpose: x_converged, f_converged and g_converged test different things and a solve is entitled to stop on any one of them. Note that solve! can also stop for reasons that are not convergence — the iteration cap, a non-finite iterate, an increase in f where one is not allowed — and none of those sets a flag here, so this is what tells the two apart; see meets_stopping_criteria.

x_converged is the one to be careful with: "the iterate stopped moving" is a statement about a ratio, and a diverging solve is where the denominator stops meaning anything. See the warning under convergence_measures for the two guards on it and for the one case they do not cover.

source
GeometricOptimizers.meets_stopping_criteria — Method
meets_stopping_criteria(status, config, iterations)

Check if the optimizer has converged.

Implementation

meets_stopping_criteria checks if one of the following is true:

  • converged (the output of SimpleSolvers.assess_convergence) is true and iterations $\geq$ config.min_iterations,
  • if config.allow_f_increases is false: status.f_increased is true,
  • iterations $\geq$ config.max_iterations,
  • status.rfₐ $>$ config.f_abstol_break,
  • any of status.x_nonfinite, status.f_nonfinite, status.g_nonfinite.

Extended help

A non-finite iterate stops the solve

No iteration can recover a NaN iterate, so the solve stops with an @error and does not spend the rest of its iteration budget.

A solve that stops here is not converged — isconverged reads the three convergence flags and none of them is set by this — so a caller that checks the status rather than only the return value can tell the two apart.

source
GeometricOptimizers.solution_scale — Method
solution_scale(x)

The norm the relative change in the iterate is measured against, i.e. the denominator of $\|x - x'\|/\|x'\|$.

For an ordinary array this is the l2norm of the iterate, which is the only scale a Euclidean problem supplies. For a compact Manifold it is not: a point of $St(N, n)$ or $Gr(n, N)$ satisfies $Y^TY = \mathbb{I}_n$, so $\|Y\|_F = \sqrt{\mathrm{tr}(Y^TY)} = \sqrt{n}$ exactly, and the scale is a constant the geometry supplies rather than something to be measured off the iterate. SymplecticStiefelManifold is non-compact — $\|U\|_F \geq \sqrt{2n}$ is unbounded on $Sp(2n, 2N)$ — so it measures l2norm(parent(U)) instead, and so does BiorthogonalManifold, on which $\|[\Phi\ \ \Psi]\|_F \geq \sqrt{2n}$ is unbounded too.

That distinction is what keeps x_converged honest on a compact manifold solve that has diverged; see convergence_measures. While a Stiefel or Grassmann iterate is on the manifold the two agree to round-off, so this changes no measurement of any converging solve — it changes what is reported once the iterate is somewhere $\sqrt{n}$ no longer describes.

A NamedTuple combines its blocks in quadrature, exactly as l2norm does, so a NamedTuple holding a compact manifold next to an ordinary array or a symplectic leaf uses the nominal scale for the first and the measured scale for the others.

source
GeometricOptimizers.OptimizerResult — Type
OptimizerResult

Serves as a diagnostic tool for the Optimizer and is the return argument of solve!.

Keys

  • status::OptimizerStatus: current status of the optimization,
  • x: solution,
  • f: function value at solution,
  • trace: one OptimizerTraceEntry per iteration if Options.store_trace was set, and empty otherwise. See trace.

Accessors

  • Base.minimum(result) is the objective at the solution, i.e. the f field,
  • solution(result) is the point,
  • status(result) is the OptimizerStatus, and trace(result) the record.

minimum is Base's. The other three are internal: solution, status and trace are neither exported nor Base.ispublic, so a caller writes GeometricOptimizers.solution(result) and so on.

minimum and not value: value evaluates an OptimizerProblem at a point, which is a different question from reading a number a finished solve already holds.

source
GeometricOptimizers.trace — Method
trace(result)

The per-iteration record solve! kept, or an empty vector if it was not asked to keep one.

Options(store_trace = true) is what asks. It is a field of SimpleSolvers.Options, and this package is what reads it.

Examples

There is one entry per iteration, and the last one agrees with the status the solve reports:

julia> f(x) = sum(x .^ 2);

julia> x = [1.0, 2.0];

julia> state = OptimizerState(Newton(), x);

julia> result = solve!(x, state, Optimizer(x, f; algorithm = Newton(), store_trace = true));

julia> length(trace(result)) == iteration_number(state)
true

julia> last(trace(result)).rg == status(result).rg
true

julia> first(trace(result)).iteration
1

Without the option there is no trace, and no error either:

julia> x = [1.0, 2.0];

julia> result = solve!(x, OptimizerState(Newton(), x), Optimizer(x, f; algorithm = Newton()));

julia> isempty(trace(result))
true

Implementation

The entries are taken from the OptimizerStatus that solve! already computes on every iteration, so nothing extra is evaluated and the cost when store_trace is unset is one Bool test per iteration.

What it is for: a statistic that has to be phase-independent. Adam at a fixed learning rate does not converge to the minimizer, it orbits it at a distance of order $\alpha$, so the error at any one iteration is a sample of an arbitrary phase on that orbit and moves with the last bits of the floating-point arithmetic. Averaging over a stretch of the orbit measures its radius instead, which is a property of $\alpha$ and the problem: across Julia versions, the final-iterate error on the problem in test/verification/svd_optim.jl changes by a factor of a few, and the mean over the last five hundred iterations by a few percent.

source
GeometricOptimizers.RiemannianGradient — Type
RiemannianGradient(gradient) <: SimpleSolvers.Gradient

A SimpleSolvers.Gradient whose value is projected onto the tangent space of the point it is evaluated at.

gradient is the Euclidean gradient, over the flattened iterate; the functor evaluates it there and then applies rgrad — leaf by leaf for a parameter set, whole for a matrix. Vector calls are forwarded unchanged, so a line search that works in coordinates sees the inner gradient and nothing else.

Implementation

This type exists to own a signature. A method of SimpleSolvers.Gradient itself on a Matrix or on a parameter set would be type piracy: the function is SimpleSolvers' and neither Base.Matrix nor NeuralNetworkParameters.NetworkParameters is this package's. The body cannot go upstream either: rgrad is the Riemannian projection of this package, and SimpleSolvers does not have it. So the gradient is wrapped, as GeometricMachineLearning does for its _GMLGradient.

Optimizer wraps for you, and only where it changes something — see _riemannian_gradient. A Manifold iterate needs no wrapper, because Manifold is this package's type and the method above is therefore already owned; wrapping one is harmless all the same, since the functor below leaves that method to handle it.

source
GeometricOptimizers.unit_matrix — Method
unit_matrix(backend, T, n)
unit_matrix(A::AbstractMatrix)

The $n\times{}n$ identity of element type T on backend, with the diagonal written by write_ones_kernel! above.

Base.one(::AbstractMatrix) is the natural spelling and is not used: Base._one allocates and then writes the diagonal in a scalar-indexed loop, which is precisely what an array on a KernelAbstractions backend cannot serve. It is the same hazard GeometricOptimizers.opnorm₁ exists to avoid one level up, and every identity this package builds goes through here rather than through Base.one — Base.one for SymmetricMatrix, SkewSymMatrix, the two AbstractTriangulars and AbstractLieAlgHorMatrix, and the $2n\times{}2n$ identities that GeometricOptimizers.𝔄 and NativePade need.

LinearAlgebra.I covers some of those uses and is not enough either. GPUArrays supplies a kernel-based +(::AbstractGPUMatrix, ::UniformScaling), so X + I is portable on the array types that package covers — but KernelAbstractions is the interface this package is written against, and a backend of its own is under no obligation to be one of them.

The matrix form takes the backend and the element type from A and its size from LinearAlgebra.checksquare, so it throws on a non-square argument exactly as Base.one does.

source
GeometricOptimizers.DEFAULT_STEP_CEILING — Constant
DEFAULT_STEP_CEILING

How far along its direction a manifold solve may step, in multiples of the manifold's natural step scale (2π on StiefelManifold and GrassmannManifold, 1 on SymplecticStiefelManifold): the c of step_αmax(c, δ), and so the params.αmax that solver_step! gives the line search through linesearch_parameters. Set it per solve with Optimizer(x, F; step_ceiling = …); Inf switches the ceiling off.

Why the solver sets a ceiling

A line search bounds its step by the merit: it stops when $\varphi$ stops falling. On a compact manifold $\varphi$ is bounded, so a step many turns too long can decrease the merit, and no test of the search rejects it. On SymplecticStiefelManifold a Hamiltonian lift $B$ can have real eigenvalues, so Cayley can have a real pole at $\alpha = 2/\rho(B)$, and Geodesic grows exponentially at a rate of up to $\rho(B)$. The bound that exists is not a property of $\varphi$: it comes from the lift's geometry and changes at every solver step. The DEFAULT_LINESEARCH_αmax of a line search method is a backstop for every problem, not this bound. The manual section A bounded merit is not a bound on the step gives the measurements on the SVD problem.

Why 1

1 says "at most one natural geometric unit along the direction": one full turn $2\pi/\|\delta\|$ on a compact orthogonal lift, and $1/\rho(B)$ — half the distance to the nearest real Cayley pole that the spectral radius allows — on a symplectic lift. That is the scale that the geometry supplies, not a value tuned to one problem.

This bounds the step, not the direction and not `α`

A short direction can take a large $\alpha$ in an ordinary step, which a ceiling on $\alpha$ alone would reject. See ensure_descent! and linesearch_rejected for the safeguards on the direction and on the outcome of the search.

Euclidean parameters do not get one

linesearch_parameters omits αmax for an AbstractVector, and passes Inf for a parameter set with no manifold block. There is no geometric scale in either case, and none is needed: $f(x + \alpha{}p)$ grows with $\alpha$, so the decrease test of the search rejects an over-long step. _manifold_αmax derives the ceiling over the manifold blocks only.

One `α`, one ceiling per block

On a parameter set the same $\alpha$ scales every block, so the ceiling is the smallest of the per-block ceilings over the manifold blocks — _manifold_αmax — and not a single bound over the norm of the whole direction, which makes every block pay for its neighbours.

source
GeometricOptimizers.Optimizer — Type
Optimizer

The optimizer that stores all the information needed for an optimization problem.

This problem can be solved by calling solve!(::AbstractVector, ::Optimizer).

Keys

Examples

F(x) = sum(sin.(x) .^ 2)
x = ones(3)
algorithm = Newton()
state = OptimizerState(algorithm, x)
optimizer = Optimizer(x, F; algorithm = algorithm, linesearch = Bisection())

solve!(x, state, optimizer)
x

# output

3-element Vector{Float64}:
 0.0
 0.0
 0.0

The choice of line search does not change which minimum this one finds, only how close to it the stopping criterion lets the solve get — Backtracking stops at 1.4e-9 per component, where Bisection above happens to land on 0 exactly:

x = ones(3)
algorithm = Newton()
state = OptimizerState(algorithm, x)
optimizer = Optimizer(x, F; algorithm = algorithm, linesearch = Backtracking())

solve!(x, state, optimizer)
F(x) < 1e-15

# output

true
This example needs the descent safeguard

$\sin^2$ has second derivative $2\cos(2x) = -0.83$ at x = 1, so the Newton direction there points uphill. ensure_descent! replaces it by the steepest-descent direction; without it both solves converge to $\pi/2$, where F is maximal.

source
GeometricOptimizers.Optimizer — Method
Optimizer(x, F; ∇F!, mode, algorithm, linesearch, retraction, observer, options_kwargs...)

Build an Optimizer for the objective F at the parameters x.

∇F! is the gradient of F. Without it, mode = :autodiff builds a forward-mode ForwardDiff gradient and mode = :finitediff a central-difference one. A vector and a Manifold take :autodiff when no mode is given. A NeuralNetworkParameters.NetworkParameters takes no default: without ∇F! and mode this throws an ArgumentError. Forward mode costs one pass of F per chunk of twelve parameters, and finite differences two evaluations of F per parameter, so either is for a small set.

linesearch is a SimpleSolvers.LinesearchMethod or a number, which is the fixed step size Static(η). algorithm, and a Static or DecayingStatic linesearch, are converted to the element type of x, so Optimizer(Float32[1, 2, 3], F; algorithm = Adam()) optimizes in Float32.

Implementation

Do not add a level of `kwargs...` here

This method splats kwargs... once. Options is built here and passed positionally from then on, so the return type of the constructor does not depend on which keywords were given; see _optimizer and the inner constructor. Nested levels of kwargs... splatting, with the construction and a solve! call in one inferred body, make the compile time superlinear on some Julia releases, and neither a barrier nor @nospecialize prevents it. KNOWN_ISSUES.md records the measurements.

source
GeometricOptimizers._optimizer — Method
_optimizer(x, problem, algorithm, linesearch, gradient, retraction, config)

Convert algorithm and linesearch to the element type of x, build the cache and the Hessian for algorithm, and hand everything to Optimizer's inner constructor.

Every argument is positional; see the implementation note of Optimizer(x, F).

source
GeometricOptimizers.default_gradient — Method
default_gradient(problem, x)

Return the SimpleSolvers.Gradient that Optimizer uses if none is supplied.

A NeuralNetworkParameters.NetworkParameters has no default gradient, and this throws an ArgumentError that names ∇F!: forward mode takes one pass per chunk of parameters, which is the wrong default for a network of more than a few hundred parameters. Supply the gradient, or opt in to forward mode or finite differences with the mode of Optimizer(x, F).

Implementation

The Manifold method is built from x: GradientAutodiff(problem.F, x) rebuilds the point before it calls problem.F, where the AbstractArray method would hand problem.F the flat vector.

On a device there is no default gradient, and every method throws an ArgumentError that names ∇F!: ForwardDiff and finite differences compute on the host.

source
GeometricOptimizers.solver_step! — Method
solver_step!(x, state, opt)

Compute a full iterate for an Optimizer.

Info

This also performs a line search.

Examples

julia> f(x) = sum(x .^ 2 + x .^ 3 / 3);

julia> x = [1f0, 2f0]
2-element Vector{Float32}:
 1.0
 2.0

julia> opt = Optimizer(x, f; algorithm = Newton());

julia> state = NewtonState(x);

julia> update!(state, gradient(opt), x);

julia> solver_step!(x, state, opt)
2-element Vector{Float32}:
 0.25
 0.6666666

Extended help

A line search that fails does not get its step taken

SimpleSolvers.solve returns a step length whether or not the search succeeded. A step taken from a failed search can be uphill: Bisection bisects $\varphi'$, so on a non-convex ray it can converge on a maximum, and it reports LINESEARCH_FLOOR. One uphill move corrupts the secant pair, and the next direction can be large enough to leave the manifold. SimpleSolvers.solve_with_status reports the outcome with the step length, so the two cases are told apart; see linesearch_rejected and restart!.

A line search that succeeds can still return a step too long for the manifold

On a compact manifold $\varphi$ is bounded, so a step many orders of magnitude too long can decrease the merit, and no test of the search rejects it. This function therefore gives the search a params.αmax through linesearch_parameters: a bound from the geometry, because $\varphi$ gives none. See DEFAULT_STEP_CEILING.

The two safeguards are independent. A rejected step is a statement about the direction, and the answer is a new direction; the ceiling is a statement about the step, and the answer is a shorter step. They meet in one place, so the rejection test takes the ceiling as an argument: a search that stops at the ceiling with the merit still falling can report LINESEARCH_FLOOR, although only the steps that this function permits fail to decrease the merit. That case keeps $Q$ and takes the step. See linesearch_rejected.

source
SimpleSolvers.solve! — Method
solve!(x, state, opt)

Solve the optimization problem described by opt::Optimizer and store the result in x.

Examples

julia> f(x) = sum(x .^ 2 + x .^ 3 / 3);

julia> x = [1f0, 2f0]
2-element Vector{Float32}:
 1.0
 2.0

julia> opt = Optimizer(x, f; algorithm = Newton());

julia> state = NewtonState(x);

julia> solve!(x, state, opt)
GeometricOptimizers.OptimizerResult{Float32, Float32, Vector{Float32}, GeometricOptimizers.OptimizerStatus{Float32, Float32}}( * Convergence measures

    |x - x'|               = 7.82e-03
    |x - x'|/|x'|          = 2.56e+02
    |f(x) - f(x')|         = 6.18e-05
    |f(x) - f(x')|/|f(x')| = 6.63e+04
    |g(x) - g(x')|         = 1.57e-02
    |g(x)|                 = 6.10e-05
, Float32[4.6478817f-8, 3.0517578f-5], 9.313341f-10, GeometricOptimizers.OptimizerTraceEntry{Float32, Float32}[])

julia> x
2-element Vector{Float32}:
 4.6478817f-8
 3.0517578f-5

julia> iteration_number(state)
4

The trailing empty vector is the per-iteration trace, which is only filled if Options(store_trace = true) asked for it.

|g(x)| is $\|\nabla{}f\|$ at the iterate that the solve returns, so g_converged fires when that residual reaches f_reltol. |g(x) - g(x')| is the difference of the gradients at the last two iterates; see gradient_difference!.

Also see solver_step!.

source
GeometricOptimizers._dot — Method
_dot(a, b)

The inner product of two gradients or directions, taken in the flattened coordinates.

Implementation

For an AbstractVecOrMat this is LinearAlgebra.dot. For a horizontal lift — or a NamedTuple of them — it is emphatically not: dot on an AbstractLieAlgHorMatrix is the ambient Frobenius product, which counts each of the off-diagonal blocks of the lift twice and so comes out exactly twice the product of the free parameters. The intrinsic coordinates are the ones every other quantity in this package is expressed in — Q is sized by the flattening, its outer products are formed there (see _flat_scratch), and the α of a line search parameterizes a curve in them — so pairing a gradient with a direction has to happen there too.

Used by trial_slope for $\varphi'(\alpha)$, by the quasi-Newton caches for $\delta^T\gamma$, whose value has to be consistent with the flattened T₁, T₂ and γ^TQγ it divides, for the predicted decrease $\widetilde{\Delta f}$, so that it is comparable with the measured $\Delta f$, and by ensure_descent!'s descent test, for the same reason.

No flat vector is built

This is the value the flattened inner product has, not the flattening. flatten writes the leaves one after another into one vector, so $\langle\mathrm{flatten}(a), \mathrm{flatten}(b)\rangle$ is the sum of the per-leaf inner products, and the sum is taken without the vectors. This matters because _dot runs once per line-search trial slope, once per OptimizerStatus, and twice per quasi-Newton update!.

The summation order is per leaf and then across, rather than one dot over the concatenation. Both are $\sum_i a_ib_i$; they differ at round-off, and test/integration/flat_buffer_allocations.jl pins the two against each other.

The grouping of the leaves does not change the sum. foldstorage threads its accumulator through the nested branches, so a left fold over a tree is the left fold over the flat leaf list whatever shape the tree has. So the same numbers written flat, written nested, and wrapped in a container all pair to the same Float64, exactly, and the test asserts == for the three of them.

source
GeometricOptimizers.PrecomputedGradient — Type
PrecomputedGradient(x, dp) <: SimpleSolvers.Gradient

A SimpleSolvers.Gradient that holds an already computed Euclidean gradient dp of the parameters x, and returns its Riemannian gradient rgrad(x, dp) when it is called on x.

This is the gradient of a training step: a training loop computes the gradient of its loss on one minibatch, and optimization_step! wraps it in this type, so the optimizer caches build the direction from it exactly as they build it from a gradient they evaluate themselves. For a parameter set, dp is a NeuralNetworkParameters.NetworkParameters of the same shape as x.

Implementation

optimization_step! passes the RiemannianGradientBuffers of its optimizer as a third argument, and the Riemannian gradient of a Stiefel or a Grassmann leaf is then written into them rather than allocated. The result is overwritten by the next call, which store_gradient! makes only after it has read the one before.

source
GeometricOptimizers.TrainingOptimizer — Type
TrainingOptimizer(x; algorithm = Adam(), linesearch = default_step_size(algorithm), retraction = Cayley(), observer = NoStepObserver())

The optimizer of a training loop: one step per minibatch, with optimization_step!.

It holds the first-order algorithm, converted once to the element type of x with change_precision, its cache and its state over the whole of x, the step-size schedule, the retraction, the buffers the retraction works in, and those the Riemannian gradient of a Stiefel or a Grassmann leaf is written into.

algorithm is a GradientMethod, a MomentumMethod, a DirectMomentum or a member of the AdamFamily; ScalarMomentAdam, DirectMomentum, DirectScalarMomentAdam and FactoredStiefelAdam step a single StiefelManifold only, and raise a MethodError for any other x. For a parameter set it may also be a CompositeMethod: then cache, state, workspace and gradient_buffer are trees of the shape of x, with the cache, the state and the buffers of each leaf for the method of that leaf. linesearch is a finite positive number, which is the fixed step size Static(η), a SimpleSolvers.Static or a DecayingStatic; the default is default_step_size(algorithm). retraction is an instance of an AbstractRetraction, Cayley() or Geodesic(). The three direct Stiefel methods retract with cayley_direct! in a DirectCayleyWorkspace, and another retraction than Cayley() is an ArgumentError for them. They form the Riemannian gradient in their own cache, so their leaf has no gradient buffer.

observer is notified of the :retraction_application phase of every step, once per leaf for a CompositeMethod; see Observing the Phases of an Optimizer Step.

Why a training step is not solve!

solve! minimizes an objective it can evaluate: its line search compares the objective along the direction, and it stops when a convergence test on the objective and its gradient passes. A training step has neither. It has the gradient of the loss on one minibatch, which is a stochastic estimate of the gradient of the loss it minimizes; the loss on that minibatch is not the objective, so there is nothing for a line search to search along and nothing for a convergence test to test. So linesearch takes a fixed or a scheduled step size and nothing else, and the loop that calls optimization_step! decides when to stop.

Examples

x = Float32[1, -2, 3]
opt = TrainingOptimizer(x; algorithm = GradientMethod(), linesearch = 0.5)
optimization_step!(x, opt, Float32[2, 2, 2])

# output

3-element Vector{Float32}:
  0.0
 -3.0
  2.0
source
GeometricOptimizers.optimization_step! — Method
optimization_step!(x, opt::TrainingOptimizer, dp)

Take one step of the training optimizer opt with the Euclidean gradient dp of the loss at x, and write the new parameters into x, which it returns.

x is the object opt was built on, and nothing else changes it between steps: the step starts from the point opt.state carries, which is x after the previous step. dp has the shape and the element type of x. An x or a dp of another element type than opt is an ArgumentError. A dp with arrays of other sizes is a DimensionMismatch, and a parameter set with other keys or another number of leaves is an ArgumentError, and so is a dp with an entry that is not finite for a GeometricOptimizers.DirectStiefelMethod. Each is raised before the iteration number moves.

The step increments the iteration number t of opt.state, reads the step size step_size(opt.linesearch, t), forms the direction of opt.method from the PrecomputedGradient of dp, scales it, retracts it with opt.retraction and copies the result into x. advance_state! then carries the state over to the new parameters. A GeometricOptimizers.DirectStiefelMethod forms the Riemannian gradient of dp in its cache instead, retracts with cayley_direct! and transports its first moment to the new point with the transport of the method. A CompositeMethod takes this step on every leaf, with the method, the cache and the state of that leaf.

For a parameter set, dp is a NeuralNetworkParameters.NetworkParameters of the same shape as x. See TrainingOptimizer for why this is not solve!.

source