tensorcircuit.backends.pytorch_backend#

Backend magic inherited from tensornetwork: pytorch backend

class tensorcircuit.backends.pytorch_backend.PyTorchBackend[源代码]#

基类:tensornetwork.backends.pytorch.pytorch_backend.PyTorchBackend, tensorcircuit.backends.abstract_backend.ExtendedBackend

See the original backend API at pytorch backend

Note the functionality provided by pytorch backend is incomplete, it currenly lacks native efficicent jit and vmap support.

__init__() None[源代码]#
abs(tensor: Any) Any[源代码]#

Returns the elementwise absolute value of tensor. :param tensor: An input tensor.

返回

Its elementwise absolute value.

返回类型

tensor

acos(a: Any) Any[源代码]#

Return the acos of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

acos of a

返回类型

Tensor

acosh(a: Any) Any[源代码]#

Return the acosh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

acosh of a

返回类型

Tensor

addition(tensor1: Any, tensor2: Any) Any[源代码]#

Return the default addition of tensor. A backend can override such implementation. :param tensor1: A tensor. :param tensor2: A tensor.

返回

Tensor

adjoint(a: Any) Any#

Return the conjugate and transpose of a tensor a

参数

a (Tensor) -- Input tensor

返回

adjoint tensor of a

返回类型

Tensor

arange(start: int, stop: Optional[int] = None, step: int = 1) Any[源代码]#

Values are generated within the half-open interval [start, stop)

参数
  • start (int) -- start index

  • stop (Optional[int], optional) -- end index, defaults to None

  • step (Optional[int], optional) -- steps, defaults to 1

返回

_description_

返回类型

Tensor

argmax(a: Any, axis: int = 0) Any[源代码]#

Return the index of maximum of an array an axis.

参数
  • a (Tensor) -- [description]

  • axis (int) -- [description], defaults to 0, different behavior from numpy defaults!

返回

[description]

返回类型

Tensor

argmin(a: Any, axis: int = 0) Any[源代码]#

Return the index of minimum of an array an axis.

参数
  • a (Tensor) -- [description]

  • axis (int) -- [description], defaults to 0, different behavior from numpy defaults!

返回

[description]

返回类型

Tensor

asin(a: Any) Any[源代码]#

Return the acos of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

asin of a

返回类型

Tensor

asinh(a: Any) Any[源代码]#

Return the asinh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

asinh of a

返回类型

Tensor

atan(a: Any) Any[源代码]#

Return the atan of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

atan of a

返回类型

Tensor

atan2(y: Any, x: Any) Any[源代码]#

Return the atan of a tensor y/x.

参数

a (Tensor) -- tensor in matrix form

返回

atan2 of a

返回类型

Tensor

atanh(a: Any) Any[源代码]#

Return the atanh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

atanh of a

返回类型

Tensor

broadcast_left_multiplication(tensor1: Any, tensor2: Any) Any[源代码]#

Perform broadcasting for multiplication of tensor1 onto tensor2, i.e. tensor1 * tensor2`, where tensor2 is an arbitrary tensor and tensor1 is a one-dimensional tensor. The broadcasting is applied to the first index of tensor2. :param tensor1: A tensor. :param tensor2: A tensor.

返回

The result of multiplying tensor1 onto tensor2.

返回类型

Tensor

broadcast_right_multiplication(tensor1: Any, tensor2: Any) Any[源代码]#

Perform broadcasting for multiplication of tensor2 onto tensor1, i.e. tensor1 * tensor2`, where tensor1 is an arbitrary tensor and tensor2 is a one-dimensional tensor. The broadcasting is applied to the last index of tensor1. :param tensor1: A tensor. :param tensor2: A tensor.

返回

The result of multiplying tensor1 onto tensor2.

返回类型

Tensor

cast(a: Any, dtype: str) Any[源代码]#

Cast the tensor dtype of a a.

参数
  • a (Tensor) -- tensor

  • dtype (str) -- "float32", "float64", "complex64", "complex128"

返回

a of new dtype

返回类型

Tensor

cholesky(tensor: Any, pivot_axis: int = - 1, non_negative_diagonal: bool = False) Tuple[Any, Any]#
concat(a: Sequence[Any], axis: int = 0) Any[源代码]#

Join a sequence of arrays along an existing axis.

参数
  • a (Sequence[Tensor]) -- [description]

  • axis (int, optional) -- [description], defaults to 0

cond(pred: bool, true_fun: Callable[[], Any], false_fun: Callable[[], Any]) Any[源代码]#

The native cond for XLA compiling, wrapper for tf.cond and limited functionality of jax.lax.cond.

参数
  • pred (bool) -- [description]

  • true_fun (Callable[[], Tensor]) -- [description]

  • false_fun (Callable[[], Tensor]) -- [description]

返回

[description]

返回类型

Tensor

conj(tensor: Any) Any#

Return the complex conjugate of tensor :param tensor: A tensor.

返回

Tensor

convert_to_tensor(tensor: Any) Any[源代码]#

Convert a np.array or a tensor to a tensor type for the backend.

coo_sparse_matrix(indices: Any, values: Any, shape: Any) Any#

Generate the coo format sparse matrix from indices and values, which is the only sparse format supported in different ML backends.

参数
  • indices (Tensor) -- shape [n, 2] for n non zero values in the returned matrix

  • values (Tensor) -- shape [n]

  • shape (Tensor) -- Tuple[int, ...]

返回

[description]

返回类型

Tensor

coo_sparse_matrix_from_numpy(a: Any) Any#

Generate the coo format sparse matrix from scipy coo sparse matrix.

参数

a (Tensor) -- Scipy coo format sparse matrix

返回

SparseTensor in backend format

返回类型

Tensor

copy(a: Any) Any[源代码]#

Return the copy of a, matrix exponential.

参数

a (Tensor) -- tensor in matrix form

返回

the copy tensor of a

返回类型

Tensor

cos(a: Any) Any[源代码]#

Return cos of tensor. :param tensor: A tensor.

返回

Tensor

cosh(a: Any) Any[源代码]#

Return the cosh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

cosh of a

返回类型

Tensor

cumsum(a: Any, axis: Optional[int] = None) Any[源代码]#

Return the cumulative sum of the elements along a given axis.

参数
  • a (Tensor) -- [description]

  • axis (Optional[int], optional) -- The default behavior is the same as numpy, different from tf/torch as cumsum of the flatten 1D array, defaults to None

返回

[description]

返回类型

Tensor

deserialize_tensor(s: str) Any#

Return a tensor given a serialized tensor string.

参数

s -- The input string representing a serialized tensor.

返回

The tensor object represented by the string.

det(a: Any) Any[源代码]#

Return the determinant scalar of a tensor a

参数

a (Tensor) -- Input tensor

返回

determinant of a

返回类型

Tensor

device(a: Any) str[源代码]#

get the universal device str for the tensor, in the format of tf

参数

a (Tensor) -- the tensor

返回

device str where the tensor lives on

返回类型

str

device_move(a: Any, dev: Any) Any[源代码]#

move tensor a to device dev

参数
  • a (Tensor) -- the tensor

  • dev (Any) -- device str or device obj in corresponding backend

返回

the tensor on new device

返回类型

Tensor

diagflat(tensor: Any, k: int = 0) Any[源代码]#

Flattens tensor and creates a new matrix of zeros with its elements on the k'th diagonal. :param tensor: A tensor. :param k: The diagonal upon which to place its elements.

返回

A new tensor with all zeros save the specified diagonal.

返回类型

tensor

diagonal(tensor: Any, offset: int = 0, axis1: int = - 2, axis2: int = - 1) Any[源代码]#

Return specified diagonals.

If tensor is 2-D, returns the diagonal of tensor with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

This function only extracts diagonals. If you wish to create diagonal matrices from vectors, use diagflat.

参数
  • tensor -- A tensor.

  • offset -- Offset of the diagonal from the main diagonal.

  • axis1 -- Axis to be used as the first/second axis of the 2D sub-arrays from which the diagonals should be taken. Defaults to second-last and last axis (note this differs from the NumPy defaults).

  • axis2 -- Axis to be used as the first/second axis of the 2D sub-arrays from which the diagonals should be taken. Defaults to second-last and last axis (note this differs from the NumPy defaults).

返回

A dim = min(1, tensor.ndim - 2) tensor storing

the batched diagonals.

返回类型

array_of_diagonals

divide(tensor1: Any, tensor2: Any) Any[源代码]#

Return the default divide of tensor. A backend can override such implementation. :param tensor1: A tensor. :param tensor2: A tensor.

返回

Tensor

dtype(a: Any) str[源代码]#

Obtain dtype string for tensor a

参数

a (Tensor) -- The tensor

返回

dtype str, such as "complex64"

返回类型

str

eigh(matrix: Any) Tuple[Any, Any][源代码]#

Compute eigenvectors and eigenvalues of a hermitian matrix.

参数

matrix -- A symetric matrix.

返回

The eigenvalues in ascending order. Tensor: The eigenvectors.

返回类型

Tensor

eigs(A: Callable, args: Optional[List[Any]] = None, initial_state: Optional[Any] = None, shape: Optional[Tuple[int, ...]] = None, dtype: Optional[Type[numpy.number]] = None, num_krylov_vecs: int = 50, numeig: int = 1, tol: float = 1e-08, which: str = 'LR', maxiter: Optional[int] = None) Tuple[Any, List]#

Arnoldi method for finding the lowest eigenvector-eigenvalue pairs of a linear operator A. A is a callable implementing the matrix-vector product. If no initial_state is provided then shape and dtype have to be passed so that a suitable initial state can be randomly generated. :param A: A (sparse) implementation of a linear operator :param arsg: A list of arguments to A. A will be called as

res = A(initial_state, *args).

参数
  • initial_state -- An initial vector for the algorithm. If None, a random initial Tensor is created using the numpy.random.randn method.

  • shape -- The shape of the input-dimension of A.

  • dtype -- The dtype of the input A. If both no initial_state is provided, a random initial state with shape shape and dtype dtype is created.

  • num_krylov_vecs -- The number of iterations (number of krylov vectors).

  • numeig -- The nummber of eigenvector-eigenvalue pairs to be computed. If numeig > 1, reorthogonalize has to be True.

  • tol -- The desired precision of the eigenvalus. Uses

  • which --

    ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which k eigenvectors and eigenvalues to find:

    'LM' : largest magnitude 'SM' : smallest magnitude 'LR' : largest real part 'SR' : smallest real part 'LI' : largest imaginary part 'SI' : smallest imaginary part

    Note that not all of those might be supported by specialized backends.

  • maxiter -- The maximum number of iterations.

返回

An array of numeig lowest eigenvalues list: A list of numeig lowest eigenvectors

返回类型

Tensor

eigsh(A: Callable, args: Optional[List[Any]] = None, initial_state: Optional[Any] = None, shape: Optional[Tuple[int, ...]] = None, dtype: Optional[Type[numpy.number]] = None, num_krylov_vecs: int = 50, numeig: int = 1, tol: float = 1e-08, which: str = 'LR', maxiter: Optional[int] = None) Tuple[Any, List]#

Lanczos method for finding the lowest eigenvector-eigenvalue pairs of a symmetric (hermitian) linear operator A. A is a callable implementing the matrix-vector product. If no initial_state is provided then shape and dtype have to be passed so that a suitable initial state can be randomly generated. :param A: A (sparse) implementation of a linear operator :param arsg: A list of arguments to A. A will be called as

res = A(initial_state, *args).

参数
  • initial_state -- An initial vector for the algorithm. If None, a random initial Tensor is created using the numpy.random.randn method.

  • shape -- The shape of the input-dimension of A.

  • dtype -- The dtype of the input A. If both no initial_state is provided, a random initial state with shape shape and dtype dtype is created.

  • num_krylov_vecs -- The number of iterations (number of krylov vectors).

  • numeig -- The nummber of eigenvector-eigenvalue pairs to be computed. If numeig > 1, reorthogonalize has to be True.

  • tol -- The desired precision of the eigenvalus. Uses

  • which --

    ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'] Which k eigenvectors and eigenvalues to find:

    'LM' : largest magnitude 'SM' : smallest magnitude 'LR' : largest real part 'SR' : smallest real part 'LI' : largest imaginary part 'SI' : smallest imaginary part

    Note that not all of those might be supported by specialized backends.

  • maxiter -- The maximum number of iterations.

返回

An array of numeig lowest eigenvalues list: A list of numeig lowest eigenvectors

返回类型

Tensor

eigsh_lanczos(A: Callable, args: Optional[List[Any]] = None, initial_state: Optional[Any] = None, shape: Optional[Tuple] = None, dtype: Optional[Type[numpy.number]] = None, num_krylov_vecs: int = 20, numeig: int = 1, tol: float = 1e-08, delta: float = 1e-08, ndiag: int = 20, reorthogonalize: bool = False) Tuple[Any, List][源代码]#

Lanczos method for finding the lowest eigenvector-eigenvalue pairs of a LinearOperator A. :param A: A (sparse) implementation of a linear operator.

Call signature of A is res = A(vector, *args), where vector can be an arbitrary Tensor, and res.shape has to be vector.shape.

参数
  • arsg -- A list of arguments to A. A will be called as res = A(initial_state, *args).

  • initial_state -- An initial vector for the Lanczos algorithm. If None, a random initial Tensor is created using the torch.randn method

  • shape -- The shape of the input-dimension of A.

  • dtype -- The dtype of the input A. If both no initial_state is provided, a random initial state with shape shape and dtype dtype is created.

  • num_krylov_vecs -- The number of iterations (number of krylov vectors).

  • numeig -- The nummber of eigenvector-eigenvalue pairs to be computed. If numeig > 1, reorthogonalize has to be True.

  • tol -- The desired precision of the eigenvalus. Uses torch.norm(eigvalsnew[0:numeig] - eigvalsold[0:numeig]) < tol as stopping criterion between two diagonalization steps of the tridiagonal operator.

  • delta -- Stopping criterion for Lanczos iteration. If a Krylov vector :math: x_n has an L2 norm \(\lVert x_n\rVert < delta\), the iteration is stopped. It means that an (approximate) invariant subspace has been found.

  • ndiag -- The tridiagonal Operator is diagonalized every ndiag iterations to check convergence.

  • reorthogonalize -- If True, Krylov vectors are kept orthogonal by explicit orthogonalization (more costly than reorthogonalize=False)

返回

(eigvals, eigvecs)

eigvals: A list of numeig lowest eigenvalues eigvecs: A list of numeig lowest eigenvectors

eigvalsh(a: Any) Any[源代码]#

Get the eigenvalues of matrix a.

参数

a (Tensor) -- tensor in matrix form

返回

eigenvalues of a

返回类型

Tensor

einsum(expression: str, *tensors: Any, optimize: bool = True) Any[源代码]#

Calculate sum of products of tensors according to expression.

eps(dtype: Type[numpy.number]) float[源代码]#

Return machine epsilon for given dtype

参数

dtype -- A dtype.

返回

Machine epsilon.

返回类型

float

exp(tensor: Any) Any#

Return elementwise exp of tensor. :param tensor: A tensor.

返回

Tensor

expm(a: Any) Any[源代码]#

Return expm log of matrix, matrix exponential. :param matrix: A tensor.

返回

Tensor

eye(N: int, dtype: Optional[str] = None, M: Optional[int] = None) Any[源代码]#
Return an identity matrix of dimension dim

Depending on specific backends, dim has to be either an int (numpy, torch, tensorflow) or a ShapeType object (for block-sparse backends). Block-sparse behavior is currently not supported

参数
  • N (int) -- The dimension of the returned matrix.

  • dtype -- The dtype of the returned matrix.

  • M (int) -- The dimension of the returned matrix.

from_dlpack(a: Any) Any[源代码]#

Transform a dlpack capsule to a tensor

参数

a (Any) -- the dlpack capsule

返回

_description_

返回类型

Tensor

gather1d(operand: Any, indices: Any) Any#

Return operand[indices], both operand and indices are rank-1 tensor.

参数
  • operand (Tensor) -- rank-1 tensor

  • indices (Tensor) -- rank-1 tensor with int dtype

返回

operand[indices]

返回类型

Tensor

get_random_state(seed: Optional[int] = None) Any#

Get the backend specific random state object.

参数

seed (Optional[int], optional) -- [description], defaults to be None

:return:the backend specific random state object :rtype: Any

gmres(A_mv: Callable, b: Any, A_args: Optional[List] = None, A_kwargs: Optional[dict] = None, x0: Optional[Any] = None, tol: float = 1e-05, atol: Optional[float] = None, num_krylov_vectors: int = 20, maxiter: Optional[int] = 1, M: Optional[Callable] = None) Tuple[Any, int]#

GMRES solves the linear system A @ x = b for x given a vector b and a general (not necessarily symmetric/Hermitian) linear operator A.

As a Krylov method, GMRES does not require a concrete matrix representation of the n by n A, but only a function vector1 = A_mv(vector0, *A_args, **A_kwargs) prescribing a one-to-one linear map from vector0 to vector1 (that is, A must be square, and thus vector0 and vector1 the same size). If A is a dense matrix, or if it is a symmetric/Hermitian operator, a different linear solver will usually be preferable.

GMRES works by first constructing the Krylov basis K = (x0, A_mv@x0, A_mv@A_mv@x0, ..., (A_mv^num_krylov_vectors)@x_0) and then solving a certain dense linear system K @ q0 = q1 from whose solution x can be approximated. For num_krylov_vectors = n the solution is provably exact in infinite precision, but the expense is cubic in num_krylov_vectors so one is typically interested in the num_krylov_vectors << n case. The solution can in this case be repeatedly improved, to a point, by restarting the Arnoldi iterations each time num_krylov_vectors is reached. Unfortunately the optimal parameter choices balancing expense and accuracy are difficult to predict in advance, so applying this function requires a degree of experimentation.

In a tensor network code one is typically interested in A_mv implementing some tensor contraction. This implementation thus allows b and x0 to be of whatever arbitrary, though identical, shape b = A_mv(x0, ...) expects. Reshaping to and from a matrix problem is handled internally.

参数
  • A_mv -- A function v0 = A_mv(v, *A_args, **A_kwargs) where v0 and v have the same shape.

  • b -- The b in A @ x = b; it should be of the shape A_mv operates on.

  • A_args -- Positional arguments to A_mv, supplied to this interface as a list. Default: None.

  • A_kwargs -- Keyword arguments to A_mv, supplied to this interface as a dictionary. Default: None.

  • x0 -- An optional guess solution. Zeros are used by default. If x0 is supplied, its shape and dtype must match those of b, or an error will be thrown. Default: zeros.

  • tol --

    Solution tolerance to achieve, norm(residual) <= max(tol*norm(b), atol). Default: tol=1E-05

    atol=tol

  • atol --

    Solution tolerance to achieve, norm(residual) <= max(tol*norm(b), atol). Default: tol=1E-05

    atol=tol

  • num_krylov_vectors --

    : Size of the Krylov space to build at each restart.

    Expense is cubic in this parameter. It must be positive. If greater than b.size, it will be set to b.size. Default: 20

  • maxiter -- The Krylov space will be repeatedly rebuilt up to this many times. Large values of this argument should be used only with caution, since especially for nearly symmetric matrices and small num_krylov_vectors convergence might well freeze at a value significantly larger than tol. Default: 1.

  • M -- Inverse of the preconditioner of A; see the docstring for scipy.sparse.linalg.gmres. This is only supported in the numpy backend. Supplying this argument to other backends will trigger NotImplementedError. Default: None.

引发

ValueError -- -if x0 is supplied but its shape differs from that of b. -in NumPy, if the ARPACK solver reports a breakdown (which usually indicates some kind of floating point issue). -if num_krylov_vectors is 0 or exceeds b.size. -if tol was negative. -if M was supplied with any backend but NumPy.

返回

The converged solution. It has the same shape as b. info : 0 if convergence was achieved, the number of restarts otherwise.

返回类型

x

grad(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False) Callable[[...], Any][源代码]#

Return the function which is the grad function of input f.

Example

>>> f = lambda x,y: x**2+2*y
>>> g = tc.backend.grad(f)
>>> g(tc.num_to_tensor(1),tc.num_to_tensor(2))
2
>>> g = tc.backend.grad(f, argnums=(0,1))
>>> g(tc.num_to_tensor(1),tc.num_to_tensor(2))
[2, 2]
参数
  • f (Callable[..., Any]) -- the function to be differentiated

  • argnums (Union[int, Sequence[int]], optional) -- the position of args in f that are to be differentiated, defaults to be 0

返回

the grad function of f with the same set of arguments as f

返回类型

Callable[..., Any]

hessian(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0) Any#
i(dtype: Optional[Any] = None) Any[源代码]#

Return 1.j in as a tensor compatible with the backend.

参数

dtype (str) -- "complex64" or "complex128"

返回

1.j tensor

返回类型

Tensor

imag(a: Any) Any[源代码]#

Return the elementwise imaginary value of a tensor a.

参数

a (Tensor) -- tensor

返回

imaginary value of a

返回类型

Tensor

implicit_randc(a: Union[int, Sequence[int], Any], shape: Union[int, Sequence[int]], p: Optional[Union[Sequence[float], Any]] = None) Any#

[summary]

参数
  • g (Any) -- [description]

  • a (Union[int, Sequence[int], Tensor]) -- The possible options

  • shape (Union[int, Sequence[int]]) -- Sampling output shape

  • p (Optional[Union[Sequence[float], Tensor]], optional) -- probability for each option in a, defaults to None, as equal probability distribution

返回

[description]

返回类型

Tensor

implicit_randn(shape: Union[int, Sequence[int]] = 1, mean: float = 0, stddev: float = 1, dtype: str = '32') Any#

Call the random normal function with the random state management behind the scene.

参数
  • shape (Union[int, Sequence[int]], optional) -- [description], defaults to 1

  • mean (float, optional) -- [description], defaults to 0

  • stddev (float, optional) -- [description], defaults to 1

  • dtype (str, optional) -- [description], defaults to "32"

返回

[description]

返回类型

Tensor

implicit_randu(shape: Union[int, Sequence[int]] = 1, low: float = 0, high: float = 1, dtype: str = '32') Any#

Call the random normal function with the random state management behind the scene.

参数
  • shape (Union[int, Sequence[int]], optional) -- [description], defaults to 1

  • mean (float, optional) -- [description], defaults to 0

  • stddev (float, optional) -- [description], defaults to 1

  • dtype (str, optional) -- [description], defaults to "32"

返回

[description]

返回类型

Tensor

index_update(tensor: Any, mask: Any, assignee: Any) Any[源代码]#

Update tensor at elements defined by mask with value assignee.

参数
  • tensor -- A Tensor object.

  • mask -- A boolean mask.

  • assignee -- A scalar Tensor. The values to assigned to tensor at positions where mask is True.

inv(matrix: Any) Any[源代码]#

Compute the matrix inverse of matrix.

参数

matrix -- A matrix.

返回

The inverse of matrix

返回类型

Tensor

is_sparse(a: Any) bool#

Determine whether the type of input a is sparse.

参数

a (Tensor) -- input matrix a

返回

a bool indicating whether the matrix a is sparse

返回类型

bool

is_tensor(a: Any) bool[源代码]#

Return a boolean on whether a is a tensor in backend package.

参数

a (Tensor) -- a tensor to be determined

返回

whether a is a tensor

返回类型

bool

item(tensor)[源代码]#

Return the item of a 1-element tensor.

参数

tensor -- A 1-element tensor

返回

The value in tensor.

jacbwd(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0) Any#

Compute the Jacobian of f using reverse mode AD.

参数
  • f (Callable[..., Any]) -- The function whose Jacobian is required

  • argnums (Union[int, Sequence[int]], optional) -- the position of the arg as Jacobian input, defaults to 0

返回

outer tuple for output, inner tuple for input args

返回类型

Tensor

jacfwd(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0) Any#

Compute the Jacobian of f using the forward mode AD.

参数
  • f (Callable[..., Any]) -- the function whose Jacobian is required

  • argnums (Union[int, Sequence[int]], optional) -- the position of the arg as Jacobian input, defaults to 0

返回

outer tuple for input args, inner tuple for outputs

返回类型

Tensor

jacrev(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0) Any#

Compute the Jacobian of f using reverse mode AD.

参数
  • f (Callable[..., Any]) -- The function whose Jacobian is required

  • argnums (Union[int, Sequence[int]], optional) -- the position of the arg as Jacobian input, defaults to 0

返回

outer tuple for output, inner tuple for input args

返回类型

Tensor

jit(f: Callable[[...], Any], static_argnums: Optional[Union[int, Sequence[int]]] = None, jit_compile: Optional[bool] = None, **kws: Any) Any[源代码]#

Return a jitted or graph-compiled version of fun for JAX backend. For all other backends returns fun. :param fun: Callable :param args: Arguments to fun. :param kwargs: Keyword arguments to fun.

返回

jitted/graph-compiled version of fun, or just fun.

返回类型

Callable

jvp(f: Callable[[...], Any], inputs: Union[Any, Sequence[Any]], v: Union[Any, Sequence[Any]]) Tuple[Union[Any, Sequence[Any]], Union[Any, Sequence[Any]]][源代码]#

Function that computes a (forward-mode) Jacobian-vector product of f. Strictly speaking, this function is value_and_jvp.

参数
  • f (Callable[..., Any]) -- The function to compute jvp

  • inputs (Union[Tensor, Sequence[Tensor]]) -- input for f

  • v (Union[Tensor, Sequence[Tensor]]) -- tangents

返回

(f(*inputs), jvp_tensor), where jvp_tensor is the same shape as the output of f

返回类型

Tuple[Union[Tensor, Sequence[Tensor]], Union[Tensor, Sequence[Tensor]]]

kron(a: Any, b: Any) Any[源代码]#

Return the kronecker product of two matrices a and b.

参数
  • a (Tensor) -- tensor in matrix form

  • b (Tensor) -- tensor in matrix form

返回

kronecker product of a and b

返回类型

Tensor

left_shift(x: Any, y: Any) Any[源代码]#

Shift the bits of an integer x to the left y bits.

参数
  • x (Tensor) -- input values

  • y (Tensor) -- Number of bits shift to x

返回

result with the same shape as x

返回类型

Tensor

log(tensor: Any) Any#

Return elementwise natural logarithm of tensor. :param tensor: A tensor.

返回

Tensor

matmul(tensor1: Any, tensor2: Any) Any[源代码]#

Perform a possibly batched matrix-matrix multiplication between tensor1 and tensor2. The following behaviour is similar to numpy.matmul: - If both arguments are 2-D they are multiplied like conventional

matrices.

  • If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

Both arguments to matmul have to be tensors of order >= 2. :param tensor1: An input tensor. :param tensor2: An input tensor.

返回

The result of performing the matmul.

返回类型

tensor

max(a: Any, axis: Optional[int] = None) Any[源代码]#

Return the maximum of an array or maximum along an axis.

参数
  • a (Tensor) -- [description]

  • axis (Optional[int], optional) -- [description], defaults to None

返回

[description]

返回类型

Tensor

mean(a: Any, axis: Optional[Sequence[int]] = None, keepdims: bool = False) Any[源代码]#

Compute the arithmetic mean for a along the specified axis.

参数
  • a (Tensor) -- tensor to take average

  • axis (Optional[Sequence[int]], optional) -- the axis to take mean, defaults to None indicating sum over flatten array

  • keepdims (bool, optional) -- _description_, defaults to False

返回

_description_

返回类型

Tensor

min(a: Any, axis: Optional[int] = None) Any[源代码]#

Return the minimum of an array or minimum along an axis.

参数
  • a (Tensor) -- [description]

  • axis (Optional[int], optional) -- [description], defaults to None

返回

[description]

返回类型

Tensor

mod(x: Any, y: Any) Any[源代码]#

Compute y-mod of x (negative number behavior is not guaranteed to be consistent)

参数
  • x (Tensor) -- input values

  • y (Tensor) -- mod y

返回

results

返回类型

Tensor

multiply(tensor1: Any, tensor2: Any) Any[源代码]#

Return the default multiplication of tensor.

A backend can override such implementation. :param tensor1: A tensor. :param tensor2: A tensor.

返回

Tensor

norm(tensor: Any) Any[源代码]#

Calculate the L2-norm of the elements of tensor

numpy(a: Any) Any[源代码]#

Return the numpy array of a tensor a, but may not work in a jitted function.

参数

a (Tensor) -- tensor in matrix form

返回

numpy array of a

返回类型

Tensor

one_hot(a: Any, num: int) Any#

See doc for onehot()

onehot(a: Any, num: int) Any[源代码]#

One-hot encodes the given a. Each index in the input a is encoded as a vector of zeros of length num with the element at index set to one:

参数
  • a (Tensor) -- input tensor

  • num (int) -- number of features in onehot dimension

返回

onehot tensor with the last extra dimension

返回类型

Tensor

ones(shape: Tuple[int, ...], dtype: Optional[str] = None) Any[源代码]#

Return an ones-matrix of dimension dim Depending on specific backends, dim has to be either an int (numpy, torch, tensorflow) or a ShapeType object (for block-sparse backends). Block-sparse behavior is currently not supported :param shape: The dimension of the returned matrix. :type shape: int :param dtype: The dtype of the returned matrix.

optimizer#

alias of tensorcircuit.backends.pytorch_backend.torch_optimizer

outer_product(tensor1: Any, tensor2: Any) Any[源代码]#

Calculate the outer product of the two given tensors.

pivot(tensor: Any, pivot_axis: int = - 1) Any#

Reshapes a tensor into a matrix, whose columns (rows) are the vectorized dimensions to the left (right) of pivot_axis.

In other words, with tensor.shape = (1, 2, 4, 5) and pivot_axis=2, this function returns an (8, 5) matrix.

参数
  • tensor -- The tensor to pivot.

  • pivot_axis -- The axis about which to pivot.

返回

The pivoted tensor.

power(a: Any, b: Union[Any, float]) Any#
Returns the exponentiation of tensor a raised to b.
If b is a tensor, then the exponentiation is element-wise

between the two tensors, with a as the base and b as the power. Note that a and b must be broadcastable to the same shape if b is a tensor.

If b is a scalar, then the exponentiation is each value in a

raised to the power of b.

参数
  • a -- The tensor containing the bases.

  • b -- The tensor containing the powers; or a single scalar as the power.

返回

The tensor that is each element of a raised to the

power of b. Note that the shape of the returned tensor is that produced by the broadcast of a and b.

probability_sample(shots: int, p: Any, status: Optional[Any] = None, g: Optional[Any] = None) Any#

Drawn shots samples from probability distribution p, given the external randomness determined by uniform distributed status tensor or backend random generator g. This method is similar with stateful_randc, but it supports status beyond g, which is convenient when jit or vmap

参数
  • shots (int) -- Number of samples to draw with replacement

  • p (Tensor) -- prbability vector

  • status (Optional[Tensor], optional) -- external randomness as a tensor with each element drawn uniformly from [0, 1], defaults to None

  • g (Any, optional) -- backend random genrator, defaults to None

返回

The drawn sample as an int tensor

返回类型

Tensor

qr(tensor: Any, pivot_axis: int = - 1, non_negative_diagonal: bool = False) Tuple[Any, Any]#

Computes the QR decomposition of a tensor. The QR decomposition is performed by treating the tensor as a matrix, with an effective left (row) index resulting from combining the axes tensor.shape[:pivot_axis] and an effective right (column) index resulting from combining the axes tensor.shape[pivot_axis:].

Example

If tensor had a shape (2, 3, 4, 5) and pivot_axis was 2, then q would have shape (2, 3, 6), and r would have shape (6, 4, 5). The output consists of two tensors Q, R such that:

Q[i1,...,iN, j] * R[j, k1,...,kM] == tensor[i1,...,iN, k1,...,kM]

Note that the output ordering matches numpy.linalg.svd rather than tf.svd.

参数
  • tensor (Tensor) -- A tensor to be decomposed.

  • pivot_axis (int, optional) -- Where to split the tensor's axes before flattening into a matrix.

  • non_negative_diagonal (bool, optional) -- a bool indicating whether the tenor is diagonal non-negative matrix.

返回

Q, the left tensor factor, and R, the right tensor factor.

返回类型

Tuple[Tensor, Tensor]

randn(shape: Tuple[int, ...], dtype: Optional[Any] = None, seed: Optional[int] = None) Any[源代码]#

Return a random-normal-matrix of dimension dim Depending on specific backends, dim has to be either an int (numpy, torch, tensorflow) or a ShapeType object (for block-sparse backends).

Block-sparse behavior is currently not supported :param shape: The dimension of the returned matrix. :type shape: int :param dtype: The dtype of the returned matrix. :param seed: The seed for the random number generator

random_split(key: Any) Tuple[Any, Any]#

A jax like split API, but it doesn't split the key generator for other backends. It is just for a consistent interface of random code; make sure you know what the function actually does. This function is mainly a utility to write backend agnostic code instead of doing magic things.

参数

key (Any) -- [description]

返回

[description]

返回类型

Tuple[Any, Any]

random_uniform(shape: Tuple[int, ...], boundaries: Optional[Tuple[float, float]] = (0.0, 1.0), dtype: Optional[Any] = None, seed: Optional[int] = None) Any[源代码]#

Return a random uniform matrix of dimension dim.

Depending on specific backends, dim has to be either an int (numpy, torch, tensorflow) or a ShapeType object (for block-sparse backends). Block-sparse behavior is currently not supported :param shape: The dimension of the returned matrix. :type shape: int :param boundaries: The boundaries of the uniform distribution. :type boundaries: tuple :param dtype: The dtype of the returned matrix. :param seed: The seed for the random number generator

返回

random uniform initialized tensor.

返回类型

Tensor

real(a: Any) Any[源代码]#

Return the elementwise real value of a tensor a.

参数

a (Tensor) -- tensor

返回

real value of a

返回类型

Tensor

relu(a: Any) Any[源代码]#

Rectified linear unit activation function. Computes the element-wise function:

\[\mathrm{relu}(x)=\max(x,0)\]
参数

a (Tensor) -- Input tensor

返回

Tensor after relu

返回类型

Tensor

reshape(tensor: Any, shape: Any) Any[源代码]#

Reshape tensor to the given shape.

参数

tensor -- A tensor.

返回

The reshaped tensor.

reshape2(a: Any) Any#

Reshape a tensor to the [2, 2, ...] shape.

参数

a (Tensor) -- Input tensor

返回

the reshaped tensor

返回类型

Tensor

reshapem(a: Any) Any#

Reshape a tensor to the [l, l] shape.

参数

a (Tensor) -- Input tensor

返回

the reshaped tensor

返回类型

Tensor

reverse(a: Any) Any[源代码]#

return a[::-1], only 1D tensor is guaranteed for consistent behavior

参数

a (Tensor) -- 1D tensor

返回

1D tensor in reverse order

返回类型

Tensor

right_shift(x: Any, y: Any) Any[源代码]#

Shift the bits of an integer x to the right y bits.

参数
  • x (Tensor) -- input values

  • y (Tensor) -- Number of bits shift to x

返回

result with the same shape as x

返回类型

Tensor

rq(tensor: Any, pivot_axis: int = 1, non_negative_diagonal: bool = False) Tuple[Any, Any]#

Computes the RQ decomposition of a tensor. The QR decomposition is performed by treating the tensor as a matrix, with an effective left (row) index resulting from combining the axes tensor.shape[:pivot_axis] and an effective right (column) index resulting from combining the axes tensor.shape[pivot_axis:].

Example

If tensor had a shape (2, 3, 4, 5) and pivot_axis was 2, then r would have shape (2, 3, 6), and q would have shape (6, 4, 5). The output consists of two tensors Q, R such that:

Q[i1,...,iN, j] * R[j, k1,...,kM] == tensor[i1,...,iN, k1,...,kM]

Note that the output ordering matches numpy.linalg.svd rather than tf.svd.

参数
  • tensor (Tensor) -- A tensor to be decomposed.

  • pivot_axis (int, optional) -- Where to split the tensor's axes before flattening into a matrix.

  • non_negative_diagonal (bool, optional) -- a bool indicating whether the tenor is diagonal non-negative matrix.

返回

Q, the left tensor factor, and R, the right tensor factor.

返回类型

Tuple[Tensor, Tensor]

scan(f: Callable[[Any, Any], Any], xs: Any, init: Any) Any#

This API follows tf.scan covention, i.e. no ys supported as jax

参数
  • f (Callable[Tuple[Tensor, Tensor], Tensor]) -- _description_

  • xs (Tensor) -- _description_

  • init (Tensor) -- _description_

返回

_description_

返回类型

Tensor

scatter(operand: Any, indices: Any, updates: Any) Any#

Roughly equivalent to operand[indices] = updates, indices only support shape with rank 2 for now.

参数
  • operand (Tensor) -- [description]

  • indices (Tensor) -- [description]

  • updates (Tensor) -- [description]

返回

[description]

返回类型

Tensor

schur(a: Any, output: str = 'real') Tuple[Any, Any]#

Compute Schur decomposition of a matrix.

参数
  • a (Tensor) -- _description_

  • output (str, optional) -- _description_, defaults to "real"

返回

T, Z so that ZTZ^H = a

返回类型

Tuple[Tensor, Tensor]

searchsorted(a: Any, v: Any, side: str = 'left') Any[源代码]#

Find indices where elements should be inserted to maintain order.

参数
  • a (Tensor) -- input array sorted in ascending order

  • v (Tensor) -- value to inserted

  • side (str, optional) -- If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a), defaults to "left"

返回

Array of insertion points with the same shape as v, or an integer if v is a scalar.

返回类型

Tensor

serialize_tensor(tensor: Any) str#

Return a string that serializes the given tensor.

参数

tensor -- The input tensor.

返回

A string representing the serialized tensor.

set_random_state(seed: Optional[int] = None, get_only: bool = False) Any#

Set the random state attached to the backend.

参数
  • seed (Optional[int], optional) -- the random seed, defaults to be None

  • get_only (bool, defaults to be False) -- If set to be true, only get the random state in return instead of setting the state on the backend

shape_concat(values: Any, axis: int) Any[源代码]#

Concatenate a sequence of tensors together about the given axis.

shape_prod(values: Any) int[源代码]#

Take the product of all of the elements in values

shape_tensor(tensor: Any) Any[源代码]#

Get the shape of a tensor.

参数

tensor -- A tensor.

返回

The shape of the input tensor returned as another tensor.

shape_tuple(tensor: Any) Tuple[Optional[int], ...][源代码]#

Get the shape of a tensor as a tuple of integers.

参数

tensor -- A tensor.

返回

The shape of the input tensor returned as a tuple of ints.

sigmoid(a: Any) Any[源代码]#

Compute sigmoid of input a

参数

a (Tensor) -- [description]

返回

[description]

返回类型

Tensor

sign(tensor: Any) Any[源代码]#

Returns an elementwise tensor with entries y[i] = 1, 0, -1 where tensor[i] > 0, == 0, and < 0 respectively.

For complex input the behaviour of this function may depend on the backend. The PyTorch version is not implemented in this case.

参数

tensor -- The input tensor.

sin(a: Any) Any[源代码]#

Return sin of tensor. :param tensor: A tensor.

返回

Tensor

sinh(a: Any) Any[源代码]#

Return the sinh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

sinh of a

返回类型

Tensor

size(a: Any) Any[源代码]#

Return the total number of elements in a in tensor form.

参数

a (Tensor) -- tensor

返回

the total number of elements in a

返回类型

Tensor

sizen(a: Any) int#

Return the total number of elements in tensor a, but in integer form.

参数

a (Tensor) -- tensor

返回

the total number of elements in tensor a

返回类型

int

slice(tensor: Any, start_indices: Tuple[int, ...], slice_sizes: Tuple[int, ...]) Any[源代码]#

Obtains a slice of a tensor based on start_indices and slice_sizes.

参数
  • tensor -- A tensor.

  • start_indices -- Tuple of integers denoting start indices of slice.

  • slice_sizes -- Tuple of integers denoting size of slice along each axis.

softmax(a: Sequence[Any], axis: Optional[int] = None) Any[源代码]#

Softmax function. Computes the function which rescales elements to the range [0,1] such that the elements along axis sum to 1.

\[\mathrm{softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}\]
参数
  • a (Sequence[Tensor]) -- Tensor

  • axis (int, optional) -- A dimension along which Softmax will be computed , defaults to None for all axis sum.

返回

concatenated tensor

返回类型

Tensor

solve(A: Any, b: Any, **kws: Any) Any[源代码]#

Solve the linear system Ax=b and return the solution x.

参数
  • A (Tensor) -- The multiplied matrix.

  • b (Tensor) -- The resulted matrix.

返回

The solution of the linear system.

返回类型

Tensor

sparse_dense_matmul(sp_a: Any, b: Any) Any#

A sparse matrix multiplies a dense matrix.

参数
  • sp_a (Tensor) -- a sparse matrix

  • b (Tensor) -- a dense matrix

返回

dense matrix

返回类型

Tensor

sparse_shape(tensor: Any) Tuple[Optional[int], ...][源代码]#
sqrt(tensor: Any) Any[源代码]#

Take the square root (element wise) of a given tensor.

sqrtmh(a: Any) Any#

Return the sqrtm of a Hermitian matrix a.

参数

a (Tensor) -- tensor in matrix form

返回

sqrtm of a

返回类型

Tensor

stack(a: Sequence[Any], axis: int = 0) Any[源代码]#

Concatenates a sequence of tensors a along a new dimension axis.

参数
  • a (Sequence[Tensor]) -- List of tensors in the same shape

  • axis (int, optional) -- the stack axis, defaults to 0

返回

concatenated tensor

返回类型

Tensor

stateful_randc(g: Any, a: Union[int, Sequence[int], Any], shape: Union[int, Sequence[int]], p: Optional[Union[Sequence[float], Any]] = None) Any#

[summary]

参数
  • g (Any) -- [description]

  • a (Union[int, Sequence[int], Tensor]) -- The possible options

  • shape (Union[int, Sequence[int]]) -- Sampling output shape

  • p (Optional[Union[Sequence[float], Tensor]], optional) -- probability for each option in a, defaults to None, as equal probability distribution

返回

[description]

返回类型

Tensor

stateful_randn(g: Any, shape: Union[int, Sequence[int]] = 1, mean: float = 0, stddev: float = 1, dtype: str = '32') Any#

[summary]

参数
  • self (Any) -- [description]

  • g (Any) -- stateful register for each package

  • shape (Union[int, Sequence[int]]) -- shape of output sampling tensor

  • mean (float, optional) -- [description], defaults to 0

  • stddev (float, optional) -- [description], defaults to 1

  • dtype (str, optional) -- only real data type is supported, "32" or "64", defaults to "32"

返回

[description]

返回类型

Tensor

stateful_randu(g: Any, shape: Union[int, Sequence[int]] = 1, low: float = 0, high: float = 1, dtype: str = '32') Any#

Uniform random sampler from low to high.

参数
  • g (Any) -- stateful register for each package

  • shape (Union[int, Sequence[int]], optional) -- shape of output sampling tensor, defaults to 1

  • low (float, optional) -- [description], defaults to 0

  • high (float, optional) -- [description], defaults to 1

  • dtype (str, optional) -- only real data type is supported, "32" or "64", defaults to "32"

返回

[description]

返回类型

Tensor

std(a: Any, axis: Optional[Sequence[int]] = None, keepdims: bool = False) Any[源代码]#

Compute the standard deviation along the specified axis.

参数
  • a (Tensor) -- _description_

  • axis (Optional[Sequence[int]], optional) -- Axis or axes along which the standard deviation is computed, defaults to None, implying all axis

  • keepdims (bool, optional) -- If this is set to True, the axes which are reduced are left in the result as dimensions with size one, defaults to False

返回

_description_

返回类型

Tensor

stop_gradient(a: Any) Any[源代码]#

Stop backpropagation from a.

参数

a (Tensor) -- [description]

返回

[description]

返回类型

Tensor

subtraction(tensor1: Any, tensor2: Any) Any[源代码]#

Return the default substraction of tensor. A backend can override such implementation. :param tensor1: A tensor. :param tensor2: A tensor.

返回

Tensor

sum(tensor: Any, axis: Optional[Sequence[int]] = None, keepdims: bool = False) Any#

Sum elements of tensor along the specified axis. Results in a new Tensor with the summed axis removed. :param tensor: An input tensor.

返回

The result of performing the summation. The order of the tensor

will be reduced by 1.

返回类型

tensor

svd(tensor: Any, pivot_axis: int = - 1, max_singular_values: Optional[int] = None, max_truncation_error: Optional[float] = None, relative: Optional[bool] = False) Tuple[Any, Any, Any, Any][源代码]#

Computes the singular value decomposition (SVD) of a tensor.

The SVD is performed by treating the tensor as a matrix, with an effective left (row) index resulting from combining the axes tensor.shape[:pivot_axis] and an effective right (column) index resulting from combining the axes tensor.shape[pivot_axis:].

For example, if tensor had a shape (2, 3, 4, 5) and pivot_axis was 2, then u would have shape (2, 3, 6), s would have shape (6), and vh would have shape (6, 4, 5).

If max_singular_values is set to an integer, the SVD is truncated to keep at most this many singular values.

If max_truncation_error > 0, as many singular values will be truncated as possible, so that the truncation error (the norm of discarded singular values) is at most max_truncation_error. If relative is set True then max_truncation_err is understood relative to the largest singular value.

If both max_singular_values and max_truncation_error are specified, the number of retained singular values will be min(max_singular_values, nsv_auto_trunc), where nsv_auto_trunc is the number of singular values that must be kept to maintain a truncation error smaller than max_truncation_error.

The output consists of three tensors u, s, vh such that: ```python

u[i1,...,iN, j] * s[j] * vh[j, k1,...,kM] == tensor[i1,...,iN, k1,...,kM]

``` Note that the output ordering matches numpy.linalg.svd rather than tf.svd.

参数
  • tensor -- A tensor to be decomposed.

  • pivot_axis -- Where to split the tensor's axes before flattening into a matrix.

  • max_singular_values -- The number of singular values to keep, or None to keep them all.

  • max_truncation_error -- The maximum allowed truncation error or None to not do any truncation.

  • relative -- Multiply max_truncation_err with the largest singular value.

返回

Left tensor factor. s: Vector of ordered singular values from largest to smallest. vh: Right tensor factor. s_rest: Vector of discarded singular values (length zero if no

truncation).

返回类型

u

switch(index: Any, branches: Sequence[Callable[[], Any]]) Any[源代码]#

branches[index]()

参数
  • index (Tensor) -- [description]

  • branches (Sequence[Callable[[], Tensor]]) -- [description]

返回

[description]

返回类型

Tensor

tan(a: Any) Any[源代码]#

Return the tan of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

tan of a

返回类型

Tensor

tanh(a: Any) Any[源代码]#

Return the tanh of a tensor a.

参数

a (Tensor) -- tensor in matrix form

返回

tanh of a

返回类型

Tensor

tensordot(a: Any, b: Any, axes: Union[int, Sequence[Sequence[int]]]) Any[源代码]#

Do a tensordot of tensors a and b over the given axes.

参数
  • a -- A tensor.

  • b -- Another tensor.

  • axes -- Two lists of integers. These values are the contraction axes.

tile(a: Any, rep: Any) Any[源代码]#

Constructs a tensor by tiling a given tensor.

参数
  • a (Tensor) -- [description]

  • rep (Tensor) -- 1d tensor with length the same as the rank of a

返回

[description]

返回类型

Tensor

to_dense(sp_a: Any) Any#

Convert a sparse matrix to dense tensor.

参数

sp_a (Tensor) -- a sparse matrix

返回

the resulted dense matrix

返回类型

Tensor

to_dlpack(a: Any) Any[源代码]#

Transform the tensor a as a dlpack capsule

参数

a (Tensor) -- _description_

返回

_description_

返回类型

Any

trace(tensor: Any, offset: int = 0, axis1: int = - 2, axis2: int = - 1) Any[源代码]#

Return summed entries along diagonals.

If tensor is 2-D, the sum is over the diagonal of tensor with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is summed.

In the PyTorch backend the trace is always over the main diagonal of the last two entries.

参数
  • tensor -- A tensor.

  • offset -- Offset of the diagonal from the main diagonal. This argument is not supported by the PyTorch backend and an error will be raised if they are specified.

  • axis1 -- Axis to be used as the first/second axis of the 2D sub-arrays from which the diagonals should be taken. Defaults to first/second axis. These arguments are not supported by the PyTorch backend and an error will be raised if they are specified.

  • axis2 -- Axis to be used as the first/second axis of the 2D sub-arrays from which the diagonals should be taken. Defaults to first/second axis. These arguments are not supported by the PyTorch backend and an error will be raised if they are specified.

返回

The batched summed diagonals.

返回类型

array_of_diagonals

transpose(tensor, perm=None) Any[源代码]#

Transpose a tensor according to a given permutation. By default the axes are reversed. :param tensor: A tensor. :param perm: The permutation of the axes.

返回

The transposed tensor

tree_flatten(pytree: Any) Tuple[Any, Any][源代码]#

Flatten python structure to 1D list

参数

pytree (Any) -- python structure to be flattened

返回

The 1D list of flattened structure and treedef which can be used for later unflatten

返回类型

Tuple[Any, Any]

tree_map(f: Callable[[...], Any], *pytrees: Any) Any[源代码]#

Return the new tree map with multiple arg function f through pytrees.

参数
  • f (Callable[..., Any]) -- The function

  • pytrees (Any) -- inputs as any python structure

引发

NotImplementedError -- raise when neither tensorflow or jax is installed.

返回

The new tree map with the same structure but different values.

返回类型

Any

tree_unflatten(treedef: Any, leaves: Any) Any[源代码]#

Pack 1D list to pytree defined via treedef

参数
  • treedef (Any) -- Def of pytree structure, the second return from tree_flatten

  • leaves (Any) -- the 1D list of flattened data structure

返回

Packed pytree

返回类型

Any

unique_with_counts(a: Any, **kws: Any) Tuple[Any, Any][源代码]#

Find the unique elements and their corresponding counts of the given tensor a.

参数

a (Tensor) -- [description]

返回

Unique elements, corresponding counts

返回类型

Tuple[Tensor, Tensor]

value_and_grad(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False) Callable[[...], Tuple[Any, Any]][源代码]#

Return the function which returns the value and grad of f.

Example

>>> f = lambda x,y: x**2+2*y
>>> g = tc.backend.value_and_grad(f)
>>> g(tc.num_to_tensor(1),tc.num_to_tensor(2))
5, 2
>>> g = tc.backend.value_and_grad(f, argnums=(0,1))
>>> g(tc.num_to_tensor(1),tc.num_to_tensor(2))
5, [2, 2]
参数
  • f (Callable[..., Any]) -- the function to be differentiated

  • argnums (Union[int, Sequence[int]], optional) -- the position of args in f that are to be differentiated, defaults to be 0

返回

the value and grad function of f with the same set of arguments as f

返回类型

Callable[..., Tuple[Any, Any]]

vectorized_value_and_grad(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0, vectorized_argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False) Callable[[...], Tuple[Any, Any]][源代码]#

Return the VVAG function of f. The inputs for f is (args[0], args[1], args[2], ...), and the output of f is a scalar. Suppose VVAG(f) is a function with inputs in the form (vargs[0], args[1], args[2], ...), where vagrs[0] has one extra dimension than args[0] in the first axis and consistent with args[0] in shape for remaining dimensions, i.e. shape(vargs[0]) = [batch] + shape(args[0]). (We only cover cases where vectorized_argnums defaults to 0 here for demonstration). VVAG(f) returns a tuple as a value tensor with shape [batch, 1] and a gradient tuple with shape: ([batch]+shape(args[argnum]) for argnum in argnums). The gradient for argnums=k is defined as

\[g^k = \frac{\partial \sum_{i\in batch} f(vargs[0][i], args[1], ...)}{\partial args[k]}\]

Therefore, if argnums=0, the gradient is reduced to

\[g^0_i = \frac{\partial f(vargs[0][i])}{\partial vargs[0][i]}\]

, which is specifically suitable for batched VQE optimization, where args[0] is the circuit parameters.

And if argnums=1, the gradient is like

\[g^1_i = \frac{\partial \sum_j f(vargs[0][j], args[1])}{\partial args[1][i]}\]

, which is suitable for quantum machine learning scenarios, where f is the loss function, args[0] corresponds to the input data and args[1] corresponds to the weights in the QML model.

参数
  • f (Callable[..., Any]) -- [description]

  • argnums (Union[int, Sequence[int]], optional) -- [description], defaults to 0

  • vectorized_argnums (Union[int, Sequence[int]], defaults to 0) -- the args to be vectorized, these arguments should share the same batch shape in the fist dimension

返回

[description]

返回类型

Callable[..., Tuple[Any, Any]]

vjp(f: Callable[[...], Any], inputs: Union[Any, Sequence[Any]], v: Union[Any, Sequence[Any]]) Tuple[Union[Any, Sequence[Any]], Union[Any, Sequence[Any]]][源代码]#

Function that computes the dot product between a vector v and the Jacobian of the given function at the point given by the inputs. (reverse mode AD relevant) Strictly speaking, this function is value_and_vjp.

参数
  • f (Callable[..., Any]) -- the function to carry out vjp calculation

  • inputs (Union[Tensor, Sequence[Tensor]]) -- input for f

  • v (Union[Tensor, Sequence[Tensor]]) -- value vector or gradient from downstream in reverse mode AD the same shape as return of function f

返回

(f(*inputs), vjp_tensor), where vjp_tensor is the same shape as inputs

返回类型

Tuple[Union[Tensor, Sequence[Tensor]], Union[Tensor, Sequence[Tensor]]]

vmap(f: Callable[[...], Any], vectorized_argnums: Union[int, Sequence[int]] = 0) Any[源代码]#

Return the vectorized map or batched version of f on the first extra axis. The general interface supports f with multiple arguments and broadcast in the fist dimension.

参数
  • f (Callable[..., Any]) -- function to be broadcasted.

  • vectorized_argnums (Union[int, Sequence[int]], defaults to 0) -- the args to be vectorized, these arguments should share the same batch shape in the fist dimension

返回

vmap version of f

返回类型

Any

vvag(f: Callable[[...], Any], argnums: Union[int, Sequence[int]] = 0, vectorized_argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False) Callable[[...], Tuple[Any, Any]]#

Return the VVAG function of f. The inputs for f is (args[0], args[1], args[2], ...), and the output of f is a scalar. Suppose VVAG(f) is a function with inputs in the form (vargs[0], args[1], args[2], ...), where vagrs[0] has one extra dimension than args[0] in the first axis and consistent with args[0] in shape for remaining dimensions, i.e. shape(vargs[0]) = [batch] + shape(args[0]). (We only cover cases where vectorized_argnums defaults to 0 here for demonstration). VVAG(f) returns a tuple as a value tensor with shape [batch, 1] and a gradient tuple with shape: ([batch]+shape(args[argnum]) for argnum in argnums). The gradient for argnums=k is defined as

\[g^k = \frac{\partial \sum_{i\in batch} f(vargs[0][i], args[1], ...)}{\partial args[k]}\]

Therefore, if argnums=0, the gradient is reduced to

\[g^0_i = \frac{\partial f(vargs[0][i])}{\partial vargs[0][i]}\]

, which is specifically suitable for batched VQE optimization, where args[0] is the circuit parameters.

And if argnums=1, the gradient is like

\[g^1_i = \frac{\partial \sum_j f(vargs[0][j], args[1])}{\partial args[1][i]}\]

, which is suitable for quantum machine learning scenarios, where f is the loss function, args[0] corresponds to the input data and args[1] corresponds to the weights in the QML model.

参数
  • f (Callable[..., Any]) -- [description]

  • argnums (Union[int, Sequence[int]], optional) -- [description], defaults to 0

  • vectorized_argnums (Union[int, Sequence[int]], defaults to 0) -- the args to be vectorized, these arguments should share the same batch shape in the fist dimension

返回

[description]

返回类型

Callable[..., Tuple[Any, Any]]

zeros(shape: Tuple[int, ...], dtype: Optional[str] = None) Any[源代码]#

Return a zeros-matrix of dimension dim Depending on specific backends, dim has to be either an int (numpy, torch, tensorflow) or a ShapeType object (for block-sparse backends).

Block-sparse behavior is currently not supported :param shape: The dimension of the returned matrix. :type shape: int :param dtype: The dtype of the returned matrix.

class tensorcircuit.backends.pytorch_backend.torch_jit_func(f: Callable[[...], Any])[源代码]#

基类:object

Delay the tracing of torch jit to the first run time: consistent with tf and jax mechanism

__init__(f: Callable[[...], Any])[源代码]#
class tensorcircuit.backends.pytorch_backend.torch_optimizer(optimizer: Any)[源代码]#

基类:object

__init__(optimizer: Any) None[源代码]#
update(grads: Any, params: Any) Any[源代码]#
tensorcircuit.backends.pytorch_backend.torchlib: Any#