Backends

Every problem in Pymanopt uses a single backend. The backend determines both how derivatives of the cost function are computed and which array type the manifold computes with and returns.

Choosing a Backend

A backend is selected by decorating the cost function with one of the decorators from pymanopt.function.

Decorator

Array type

Automatic differentiation

pip extra

pymanopt.function.numpy()

numpy.ndarray

no

none

pymanopt.function.autograd()

numpy.ndarray

yes

autograd

pymanopt.function.jax()

jax.Array

yes

jax

pymanopt.function.pytorch()

torch.Tensor

yes

torch

pymanopt.function.tensorflow()

tf.Tensor

yes

tensorflow

With the NumPy backend, derivatives must be passed to pymanopt.core.problem.Problem explicitly, e.g. via its euclidean_gradient argument.

The signature of the decorated callable must match the point layout of the manifold it is defined on. For instance, for memory efficiency points on the pymanopt.manifolds.fixed_rank.FixedRankEmbedded manifold are not represented as m x n matrices in the ambient space but rather as singular value decompositions. As such a cost function defined on the manifold must accept three arguments u, s and vt. Refer to the documentation of the respective manifold on how points are represented.

How a Manifold Gets Its Backend

A manifold created without a backend adopts the backend of the cost function when both are passed to pymanopt.core.problem.Problem.

manifold = pymanopt.manifolds.Sphere(3)

@pymanopt.function.pytorch(manifold)
def cost(point):
    return -point @ matrix @ point

problem = pymanopt.Problem(manifold, cost)  # manifold now uses PyTorch

To use a manifold outside of a problem, e.g. to sample points or to call pymanopt.tools.diagnostics.check_retraction(), pass a backend instance to its constructor.

from pymanopt.backends.numpy_backend import NumpyBackend

manifold = pymanopt.manifolds.Sphere(3, backend=NumpyBackend())
point = manifold.random_point()

If the manifold already has a backend, callables passed to pymanopt.core.problem.Problem need not be decorated. Decorated ones must use the same backend and precision as the manifold. The same holds for the manifolds making up a pymanopt.manifolds.product.Product manifold.

Arrays

Points and tangent vectors are arrays of the backend’s array type. This includes the point attribute of the result returned by an optimizer and an initial_point passed to it. Constants used in a cost function should also be arrays of that type, e.g. torch.from_numpy(matrix) for a NumPy array matrix.

Precision and Complex Manifolds

Backends use real double precision numbers by default. The decorators and the backend classes accept a dtype argument, e.g. torch.float32 for single precision.

Whether a manifold computes with real or complex numbers is determined by the manifold itself. If the dtype of the backend does not match, the manifold switches to the real or complex data type of the same precision and emits a warning. To avoid it on complex manifolds such as pymanopt.manifolds.grassmann.ComplexGrassmann, pass a complex dtype.

from pymanopt.backends.jax_backend import JaxBackend

@pymanopt.function.jax(manifold, dtype=JaxBackend.DEFAULT_COMPLEX_DTYPE())
def cost(point):
    ...

Extending Pymanopt

Custom manifolds should accept a backend argument, forward it to the constructor of pymanopt.manifolds.manifold.Manifold, and use self.backend instead of NumPy for all computations, e.g. self.backend.linalg_norm(tangent_vector).

New backends can be created by inheriting from the pymanopt.backends.backend.Backend class, and creating a backend decorator using pymanopt.function.decorator_factory().

my_backend = pymanopt.function.decorator_factory(
    "my_package.my_module", "MyBackend"
)

Function Decorators

class pymanopt.function.Function(*, function, manifold, backend)[source]

Bases: object

Parameters:
get_gradient_operator()[source]
get_hessian_operator()[source]
pymanopt.function.decorator_factory(module, backend_class)[source]

Create a backend decorator.

Parameters:
  • module (str) – Name of the module defining the backend class, e.g. "pymanopt.backends.jax_backend". It is imported when a function is decorated.

  • backend_class (str) – Name of the backend class in module.

Returns:

A decorator taking a manifold and an optional dtype.

Return type:

_ObjectiveFunctionDecorator

pymanopt.function.autograd(manifold, dtype=None)
Parameters:
  • manifold (Manifold)

  • dtype (Any | None)

Return type:

Callable[[Callable[[…], Any]], Function]

pymanopt.function.jax(manifold, dtype=None)
Parameters:
  • manifold (Manifold)

  • dtype (Any | None)

Return type:

Callable[[Callable[[…], Any]], Function]

pymanopt.function.numpy(manifold, dtype=None)
Parameters:
  • manifold (Manifold)

  • dtype (Any | None)

Return type:

Callable[[Callable[[…], Any]], Function]

pymanopt.function.pytorch(manifold, dtype=None)
Parameters:
  • manifold (Manifold)

  • dtype (Any | None)

Return type:

Callable[[Callable[[…], Any]], Function]

pymanopt.function.tensorflow(manifold, dtype=None)
Parameters:
  • manifold (Manifold)

  • dtype (Any | None)

Return type:

Callable[[Callable[[…], Any]], Function]

Backend Interface

class pymanopt.backends.backend.Backend[source]

Bases: ABC

Abstract base class defining the interface for backends.

A backend provides automatic differentiation of cost functions and the numerical functions used by manifolds.

abstract property dtype: type
abstract property dtype_precision: DTypePrecision
abstract property is_dtype_real: bool
abstract static DEFAULT_REAL_DTYPE()[source]
Return type:

type

abstract static DEFAULT_COMPLEX_DTYPE()[source]
Return type:

type

abstract to_complex_backend()[source]
Return type:

Backend

abstract to_real_backend()[source]
Return type:

Backend

abstract generate_gradient_operator(function, num_arguments)[source]

Creates a function to compute gradients of a function.

Parameters:
  • function – A callable.

  • num_arguments – The number of arguments that function expects.

Returns:

A Python callable of the gradient of function accepting arguments according to the signature defined by arguments.

Return type:

Callable

abstract generate_hessian_operator(function, num_arguments)[source]

Creates a function to compute Hessian-vector products of a function.

Parameters:
  • function – A callable.

  • num_arguments – The number of arguments that function expects.

Returns:

A Python callable evaluating the Hessian-vector product of function accepting arguments according to the signature defined by arguments. The returned callable accepts a point of evaluation as a sequence of length num_arguments, as well as a vector of the same shape that is right-multiplied to the Hessian.

Return type:

Callable

abs(array)[source]

Element-wise absolute value, like numpy.absolute().

Parameters:

array (array_t)

Return type:

array_t

all(array)[source]

Test whether all elements are true, like numpy.all().

Parameters:

array (array_t)

Return type:

bool

allclose(array_a, array_b, rtol, atol)[source]

Test closeness with rtol and atol, like numpy.allclose().

Parameters:
  • array_a (array_t)

  • array_b (array_t)

  • rtol (float)

  • atol (float)

Return type:

bool

any(array)[source]

Test whether any element is true, like numpy.any().

Parameters:

array (array_t)

Return type:

bool | None

arange(start, stop=None, step=None)[source]

Evenly spaced values excluding stop, like numpy.arange().

Parameters:
  • start (int)

  • stop (int | None)

  • step (int | None)

Return type:

array_t

arccos(array)[source]

Element-wise arc cosine, like numpy.arccos().

Parameters:

array (array_t)

Return type:

array_t

arccosh(array)[source]

Inverse hyperbolic cosine, like numpy.arccosh().

Parameters:

array (array_t)

Return type:

array_t

arctan(array)[source]

Element-wise arc tangent, like numpy.arctan().

Parameters:

array (array_t)

Return type:

array_t

arctanh(array)[source]

Inverse hyperbolic tangent, like numpy.arctanh().

Parameters:

array (array_t)

Return type:

array_t

argmin(array)[source]

Flat index of the minimum, like numpy.argmin().

Parameters:

array (array_t)

Return type:

array_t

argsort(array)[source]

Indices that sort the last axis, like numpy.argsort().

Parameters:

array (array_t)

Return type:

array_t

array(array)[source]

Convert to the backend’s dtype, like numpy.asarray().

Parameters:

array (array_t)

Return type:

array_t

assert_allclose(array_a, array_b, rtol=1e-06, atol=1e-06)[source]

Raise ValueError unless arrays are close within tolerances.

Parameters:
  • array_a (array_t)

  • array_b (array_t)

  • rtol (float)

  • atol (float)

Return type:

None

assert_equal(array_a, array_b)[source]

Raise ValueError unless arrays are exactly equal.

Parameters:
  • array_a (array_t)

  • array_b (array_t)

Return type:

None

concatenate(arrays, axis=0)[source]

Join arrays on an existing axis, like numpy.concatenate().

Parameters:
  • arrays (list[array_t] | tuple[array_t, ...])

  • axis (int)

Return type:

array_t

conjugate(array)[source]

Element-wise complex conjugate, like numpy.conjugate().

Parameters:

array (array_t)

Return type:

array_t

conjugate_transpose(array)[source]

Conjugate and swap the last two axes, preserving leading axes.

Parameters:

array (array_t)

Return type:

array_t

cos(array)[source]

Element-wise cosine, like numpy.cos().

Parameters:

array (array_t)

Return type:

array_t

diag(array)[source]

Extract or construct a diagonal, like numpy.diag().

Parameters:

array (array_t)

Return type:

array_t

diagonal(array, axis1, axis2)[source]

Extract the diagonal along two axes, like numpy.diagonal().

Parameters:
  • array (array_t)

  • axis1 (int)

  • axis2 (int)

Return type:

array_t

eps()[source]

Gap from 1 to the next larger value at the backend’s precision.

Return type:

float

exp(array)[source]

Element-wise exponential, like numpy.exp().

Parameters:

array (array_t)

Return type:

array_t

expand_dims(array, axis)[source]

Insert a length-one axis, like numpy.expand_dims().

Parameters:
  • array (array_t)

  • axis (int)

Return type:

array_t

eye(size)[source]

Identity in the backend’s dtype, like numpy.eye().

Parameters:

size (int)

Return type:

array_t

hstack(arrays)[source]

Stack arrays horizontally, like numpy.hstack().

Parameters:

arrays (list[array_t] | tuple[array_t, ...])

Return type:

array_t

herm(array)[source]

Hermitian part (A + A*) / 2 over the last two axes.

Parameters:

array (array_t)

Return type:

array_t

imag(array)[source]

Element-wise imaginary part, like numpy.imag().

Parameters:

array (array_t)

Return type:

array_t

iscomplexobj(array)[source]

Test for a complex dtype, like numpy.iscomplexobj().

Parameters:

array (array_t)

Return type:

bool

isnan(array)[source]

Element-wise test for NaN, like numpy.isnan().

Parameters:

array (array_t)

Return type:

array_t

isrealobj(array)[source]

Test for a non-complex dtype, like numpy.isrealobj().

Parameters:

array (array_t)

Return type:

bool

linalg_cholesky(array)[source]

Lower Cholesky factors, like numpy.linalg.cholesky().

Parameters:

array (array_t)

Return type:

array_t

linalg_det(array)[source]

Determinant on the last two axes, like numpy.linalg.det().

Parameters:

array (array_t)

Return type:

array_t

linalg_eigh(array)[source]

Hermitian eigenpairs, like numpy.linalg.eigh().

Parameters:

array (array_t)

Return type:

tuple[array_t, array_t]

linalg_eigvalsh(array_x, array_y=None)[source]

Hermitian eigenvalues over the last two axes.

Parameters:
  • array_x (array_t) – Symmetric or Hermitian matrices.

  • array_y (array_t | None) – Positive definite matrices for the generalized problem array_x @ v = w * array_y @ v; None uses the identity.

Return type:

array_t

linalg_expm(array, symmetric=False)[source]

Matrix exponential over the last two axes, preserving leading axes.

Parameters:
  • array (array_t) – Square matrices.

  • symmetric (bool) – Assume symmetric or Hermitian matrices and use their eigendecomposition.

Return type:

array_t

linalg_inv(array)[source]

Inverse over the last two axes, like numpy.linalg.inv().

Parameters:

array (array_t)

Return type:

array_t

linalg_matrix_rank(array)[source]

Numerical matrix rank, like numpy.linalg.matrix_rank().

Parameters:

array (array_t)

Return type:

int

linalg_logm(array, positive_definite=False)[source]

Matrix logarithm over the last two axes, preserving leading axes.

Parameters:
  • array (array_t) – Square matrices.

  • positive_definite (bool) – Assume symmetric or Hermitian positive definite matrices and use their eigendecomposition.

Return type:

array_t

linalg_norm(array, ord=None, axis=None, keepdims=False)[source]

Vector or matrix norm, like numpy.linalg.norm().

Parameters:
  • array (array_t)

  • ord (int | Literal['fro'] | None)

  • axis (int | list[int] | tuple[int, ...] | None)

  • keepdims (bool)

Return type:

array_t

linalg_qr(array)[source]

Reduced QR on the last two axes, with nonnegative diagonal of R.

Parameters:

array (array_t)

Return type:

tuple[array_t, array_t]

linalg_solve(array_a, array_b)[source]

Solve array_a @ x = array_b, like numpy.linalg.solve().

Parameters:
  • array_a (array_t)

  • array_b (array_t)

Return type:

array_t

linalg_solve_continuous_lyapunov(array_a, array_q)[source]

Solve A @ X + X @ A* = Q, where A* is the adjoint of A.

Parameters:
  • array_a (array_t)

  • array_q (array_t)

Return type:

array_t

linalg_svd(array, full_matrices=True)[source]

Return U, s, Vh, like numpy.linalg.svd().

Parameters:
  • array (array_t)

  • full_matrices (bool)

Return type:

tuple[array_t, array_t, array_t]

linalg_svdvals(array)[source]

Singular values, like numpy.linalg.svdvals().

Parameters:

array (array_t)

Return type:

array_t

log(array)[source]

Element-wise natural logarithm, like numpy.log().

Parameters:

array (array_t)

Return type:

array_t

log10(array)[source]

Element-wise base-10 logarithm, like numpy.log10().

Parameters:

array (array_t)

Return type:

array_t

logical_not(array)[source]

Element-wise logical negation, like numpy.logical_not().

Parameters:

array (array_t)

Return type:

array_t

logspace(start, stop, num)[source]

Base-10 spacing in backend dtype, like numpy.logspace().

Parameters:
  • start (float)

  • stop (float)

  • num (int)

Return type:

array_t

matvec(A, x)[source]

Multiply a matrix by a vector using A @ x.

Parameters:
  • A (array_t)

  • x (array_t)

Return type:

array_t

matmul(A, B)[source]

Matrix product, broadcasting batches, like numpy.matmul().

Parameters:
  • A (array_t)

  • B (array_t)

Return type:

array_t

multieye(k, n)[source]

Stack k identity matrices into shape (k, n, n).

Parameters:
  • k (int)

  • n (int)

Return type:

array_t

ndim(array)[source]

Number of array dimensions, like numpy.ndim().

Parameters:

array (array_t)

Return type:

int

newaxis = None
ones(shape)[source]

Ones in the backend’s dtype, like numpy.ones().

Parameters:

shape (list[int] | tuple[int, ...])

Return type:

array_t

ones_bool(shape)[source]

Boolean array filled with True.

Parameters:

shape (list[int] | tuple[int, ...])

Return type:

array_t

pi = 3.141592653589793
prod(array)[source]

Product of all elements, like numpy.prod().

Parameters:

array (array_t)

Return type:

float

random_normal(loc=0.0, scale=1.0, size=None)[source]

Normal samples in the backend’s dtype.

Complex samples have independent real and imaginary parts, each with the given mean and standard deviation.

Parameters:
  • loc (float) – Mean of each real component.

  • scale (float) – Standard deviation of each real component.

  • size (int | list[int] | tuple[int, ...] | None) – Sample shape; None draws a single sample.

Return type:

array_t

random_randn(*dims)[source]

Standard normal samples of shape dims, via random_normal().

Parameters:

dims (int)

Return type:

array_t

random_uniform(size=None)[source]

Uniform samples in [0, 1) in the backend’s dtype.

Complex samples have independent parts in [0, 1).

Parameters:

size (int | list[int] | tuple[int, ...] | None) – Sample shape; None draws a single sample.

Return type:

array_t

real(array)[source]

Element-wise real part, like numpy.real().

Parameters:

array (array_t)

Return type:

array_t

reshape(array, shape)[source]

Reshape, preserving element order, like numpy.reshape().

Parameters:
  • array (array_t)

  • shape (list[int] | tuple[int, ...])

Return type:

array_t

sin(array)[source]

Element-wise sine, like numpy.sin().

Parameters:

array (array_t)

Return type:

array_t

sinc(array)[source]

Normalized sinc, sin(pi*x)/(pi*x), like numpy.sinc().

Parameters:

array (array_t)

Return type:

array_t

skew(array)[source]

Skew-symmetric part (A - A.T) / 2 over the last two axes.

Parameters:

array (array_t)

Return type:

array_t

skewh(array)[source]

Skew-Hermitian part (A - A*) / 2 over the last two axes.

Parameters:

array (array_t)

Return type:

array_t

sort(array, descending=False)[source]

Sort the last axis in ascending or descending order.

Parameters:
  • array (array_t)

  • descending (bool)

Return type:

array_t

special_comb(n, k)[source]

Ways to choose k from n, like scipy.special.comb().

Parameters:
  • n (int)

  • k (int)

sqrt(array)[source]

Element-wise square root, like numpy.sqrt().

Parameters:

array (array_t)

Return type:

array_t

squeeze(array)[source]

Remove all length-one axes, like numpy.squeeze().

Parameters:

array (array_t)

Return type:

array_t

stack(arrays, axis=0)[source]

Join arrays along a new axis, like numpy.stack().

Parameters:
  • arrays (list[array_t] | tuple[array_t, ...])

  • axis (int)

Return type:

array_t

sum(array, axis=None, keepdims=False)[source]

Sum over axes, or all axes if None, like numpy.sum().

Parameters:
  • array (array_t)

  • axis (int | list[int] | tuple[int, ...] | None)

  • keepdims (bool)

Return type:

array_t

sym(array)[source]

Symmetric part (A + A.T) / 2 over the last two axes.

Parameters:

array (array_t)

Return type:

array_t

tan(array)[source]

Element-wise tangent, like numpy.tan().

Parameters:

array (array_t)

Return type:

array_t

tanh(array)[source]

Element-wise hyperbolic tangent, like numpy.tanh().

Parameters:

array (array_t)

Return type:

array_t

tensordot(a, b, axes=2)[source]

Tensor contraction, like numpy.tensordot().

Parameters:
  • a (array_t) – First input array.

  • b (array_t) – Second input array.

  • axes (int) – Number of trailing axes of a to contract with leading axes of b.

Return type:

array_t

tile(array, reps)[source]

Repeat an array along each axis, like numpy.tile().

Parameters:
  • array (array_t)

  • reps (int | list[int] | tuple[int, ...])

Return type:

array_t

trace(array)[source]

Sum the diagonal on the last two axes, preserving leading axes.

Parameters:

array (array_t)

Return type:

array_t

transpose(array)[source]

Swap the last two axes without conjugation; keep leading axes.

Parameters:

array (array_t)

Return type:

array_t

triu(array, k=0)[source]

Upper triangle on the last two axes, like numpy.triu().

Parameters:
  • array (array_t) – Input matrices.

  • k (int) – Diagonal offset; positive is above the main diagonal.

Return type:

array_t

vstack(arrays)[source]

Stack arrays vertically, like numpy.vstack().

Parameters:

arrays (list[array_t] | tuple[array_t, ...])

Return type:

array_t

where(condition, x, y)[source]

Select elements or find true indices, like numpy.where().

Parameters:
  • condition (array_t) – Boolean selection mask.

  • x (array_t | None) – Values at true entries; use None with y=None to return indices of true entries instead.

  • y (array_t | None) – Values at false entries; must be supplied together with x.

Return type:

array_t | tuple[array_t, …]

zeros(shape)[source]

Zeros in the backend’s dtype, like numpy.zeros().

Parameters:

shape (list[int] | tuple[int, ...])

Return type:

array_t

zeros_bool(shape)[source]

Boolean array filled with False.

Parameters:

shape (list[int] | tuple[int, ...])

Return type:

array_t

zeros_like(array)[source]

Zeros in backend dtype, like numpy.zeros_like().

Parameters:

array (array_t)

Return type:

array_t