Module api_specification

Module api_specification 

Source
Expand description

§API Specification of RSTSR

§Notes on API Specification

  • “type” column
    • “assoc” is abbreviation for “associated method function”, meaning that it can only be called by something like tensor.foo() instead of rt::foo().
    • “assoc/fn” means that this function is both defined as associated method and usual function.
    • “core ops” refers to core::ops, indicating that it implements rust language’s own operator.
  • Function variants
    • Tables in this page will not show function variants. For more details, please see documentation (under construction) of each function / associated methods.
    • Fallible variants:
      • Infallible (panics when error) are not decorated;
      • Fallible (function that returns RSTSR’s own Result) are decorated with _f suffix;
      • For example infallible asarray and fallible asarray_f.
    • Pass-by-value/reference variants:
      • Pass-by-value (consumes the original tensor, foo(self, ...)) are decorated with into_ prefix;
      • Pass-by-reference (does not consumes the original tensor, foo(&self, ...)) may have to_ prefix or none;
      • For example pass-by-value into_transpose or pass-by-reference transpose.
    • TensorCow output type variants:
      • Pass-by-value returning TensorCow, decorated with change_ prefix;
      • Pass-by-value returning Tensor, decorated with into_ prefix;
      • Pass-by-reference returning TensorView, decorated with to_ prefix or none;
      • reshape and to_layout fits into this category.

§Tensor Structure and Ownership

§Figure illustration of tensor structure

rstsr-basic-structure

§Tensor

TypeIdentifierMinimal Description
moduletensorbaseDefining tensor structs.
structTensorBase<S, D>Basic struct of tensor (storage + layout).
aliasTensorAny<R, T, B, D>Basic struct of tensor (data with lifetime + device backend + layout).
aliasTensor<T, B, D>Tensor that owns its raw data.
aliasTensorView<'l, T, B, D>
TensorRef<'l, T, B, D>
Tensor that shares its raw data by reference.
aliasTensorMut<'l, T, B, D>
TensorViewMut<'l, T, B, D>
Tensor that shares its raw data by mutable reference.
aliasTensorCow<'l, T, B, D>Tensor either shares its raw data by reference, or owns its raw data (immutable). Cow refers to copy-on-write.
aliasTensorArc<T, B, D>Tensor with its raw data wrapped by atomic reference-counter pointer (Arc).

§Tensor Layout

TypeIdentifierMinimal Description
module[layout][crate::layout]Defining layout of tensor and dimensionality.
structLayout<D>Layout of tensor.
traitDimAPIMain basic interface for dimensionality.
aliasIxDDynamic dimensionality (alias to Vec<usize>).
aliasIx<N>Fixed dimensionality (alias to [usize; N]).

§Device

TypeIdentifierMinimal Description
modulestorage::deviceDefining storage and device.
structDeviceCpuSerialBasic backend that handles computations in single thread.
structDeviceFaerBackend that applies multi-threaded operations (by rayon) and efficient matmul (by faer).
structDeviceCpuRayonBase backend for rayon paralleled devices (device for developer, not user).
traitDeviceAPI<T>Main basic interface for device.

Device is designed to be able extended by other crates. The above devices DeviceCpuSerial and DeviceFaer are only special in that they are realized in rstsr-core. We hope that in future, more devices (backends) can be supported.

§Storage

TypeIdentifierMinimal Description
modulestorage::deviceDefining storage and device.
structStorage<R, T, B>Storage of tensor (data with lifetime + device backend)

§Tensor Ownership

TypeIdentifierMinimal Description
modulestorage::dataDefining data representations (lifetime or the way raw data are stored).
structDataOwned<C>Struct wrapper for owned raw data.
enumDataRef<'l, C>Enum wrapper for reference of raw data (or manually-dropped data).
enumDataMut<'l, C>Enum wrapper for mutable reference of raw data (or manually-dropped data).
enumDataCow<'l, C>Enum wrapper for mutable reference of raw data (or manually-dropped data).
structDataArc<C>Struct wrapper for atomic reference-counted raw data pointer.
traitDataAPIInterface of immutable operations for data representations.
traitDataCloneAPIInterface of underlying data cloning for data representations.
traitDataMutAPIInterface of mutable operations for data representations.
traitDataIntoCowAPI<'l>Interface for generating DataCow<'l, C>.
traitDataForceMutAPIInterface for generating mutable reference, ignoring lifetime and borrow checks.

§Indexing

TypeIdentifierMinimal Description
assoc/fnslice
slice_mut
Basic slicing to tensor, generating view of smaller tensor.
associ
i_mut
Alias to slice and slice_mut.
core opsoperator []
Index
IndexMut
Indexing tensor element, giving reference of scalar value (not efficient due to boundary check).
associndex_uncheck
index_mut_uncheck
Indexing tensor element, giving reference of scalar value.

§RSTSR Specific Identifiers

§Ownership change and transfer

TypeIdentifierMinimal Description
moduleownership_conversion
assocviewGet a view of tensor.
assocview_mutGet a mutable view of tensor.
associnto_cowConvert current tensor into copy-on-write.
associnto_ownedConvert tensor into owned tensor (Tensor). Raw data is try to be moved, or the necessary values cloned.
associnto_sharedConvert tensor into shared tensor (TensorArc). Raw data is try to be moved, or the necessary values cloned.
assocto_ownedClone necessary values to owned tensor (Tensor) without destroying original tensor.
assocforce_mutForce generate mutable view of tensor, ignoring lifetime and borrow check.
assocto_vecClone 1-D tensor to Vec<T>.
associnto_vecMove 1-D tensor to Vec<T> if possible, otherwise clone.
assocto_scalarExtract scalar value from tensor that only have one element.
assocas_ptr
as_mut_ptr
Returns pointer to the first element in tensor.
fnasarrayConvert input (scalar, Vec<T>, &[T], tensor) to an array, optionally with shape/layout specified.
assocTensorBase::into_raw_partsDestruct tensor into storage and layout.
assocStorage::into_raw_partsDestruct storage into data (with lifetime) and device.
assocDataOwned::into_rawDestruct owned data and get the raw data (Vec<T> for CPU devices).
assocTensorBase::raw
TensorBase::raw_mut
Get reference of raw data.

§Iteration

TypeIdentifierMinimal Description
moduleiterator_elemTensor iterators that gives elements.
associter
iter_mut
Iterate tensor by default ordering (c-prefer or f-prefer).
associter_with_order
iter_mut_with_order
Iterate tensor with specified order.
associndexed_iter
indexed_iter_mut
Enumerate tensor by default ordering (c-prefer or f-prefer).
associndexed_iter_with_order
indexed_iter_mut_with_order
Enumerate tensor with specified order.
moduleiterator_axesAxes iterators that gives smaller tensor views.
assocaxes_iter
axes_iter_mut
Iterate tensor by axes by default ordering (c-prefer or f-prefer).
assocaxes_iter_with_order
axes_iter_mut_with_order
Iterate tensor by axes with specified order.
associndexed_axes_iter
indexed_axes_iter_mut
Enumerate tensor by axes by default ordering (c-prefer or f-prefer).
associndexed_axes_iter_with_order
indexed_axes_iter_mut_with_order
Enumerate tensor by axes with specified order.

§Mapping

TypeIdentifierMinimal Description
modulemap_elementwiseElementwise mapping of tensor.
assocmap
map_fnmut
Call function by reference on each element to create a new tensor.
assocmapv
mapv_fnmut
Call function by value on each element to create a new tensor.
assocmapi
mapi_fnmut
Modify the tensor in place by calling function by mutable reference on each element.
assocmapvi
mapvi_fnmut
Modify the tensor in place by calling function by reference on each element.
assocmapb
mapb_fnmut
Map to another tensor and call function by reference on each element to create a new tensor.
assocmapvb
mapvb_fnmut
Map to another tensor and call function by value on each element to create a new tensor.

§Error handling

TypeIdentifierMinimal Description
module[error][crate::error]Error handling in RSTSR.
enumErrorError type in RSTSR.
alias[Result<E>][crate::error::Result]Result type in RSTSR.

§Flags

TypeIdentifierMinimal Description
flags[flags][crate::flags]Flags for tensor.
enumFlagOrderThe order of tensor.
enumFlagDiagUnit-diagonal of matrix.
enumFlagSideSide of matrix operation.
enumFlagTransTransposition of matrix operation.
enumFlagUpLoUpper/Lower triangular of matrix operation.
enumFlagSymmSymmetric of matrix operation.
enumTensorIterOrderThe policy of tensor iterator.

§Tensor Manuplication

§Storage-irrelevent manuplication

TypeIdentifierMinimal Description
fnbroadcast_arraysBroadcasts any number of arrays against each other.
assoc/fnto_broadcastBroadcasts an array to a specified shape.
assoc/fnexpand_dimsExpands the shape of an array by inserting a new axis (dimension) of size one at the position specified by axis.
assoc/fnflipReverses the order of elements in an array along the given axis.
assoc/fnpermute_dims
transpose
Permutes the axes (dimensions) of an array x.
assoc/fnreverse_axesReverse the order of elements in an array along the given axis.
assoc/fnswapaxesInterchange two axes of an array.
assoc/fnsqueezeRemoves singleton dimensions (axes) from x.
assoc/fnto_dim
to_dyn
Convert layout to the other dimension.
assoc/fnreshape_assume_contigAssuming contiguous array, reshapes an array without changing its data.

§Storage-dependent manuplication

TypeIdentifierMinimal Description
assoc/fnreshape
into_shape
change_shape
Reshapes an array without changing its data.
assoc/fnto_layout
into_layout
change_layout
Convert tensor to the other layout.

§Storage-creation manuplication

These functions are to be realized in future (concat, stack, etc).

§Tensor Creation

TypeIdentifierMinimal Description
fnasarrayConvert input (scalar, Vec<T>, &[T], tensor) to an array, optionally with shape/layout specified.
modulecrate::tensor::creationCreation methods for tensor.
fnarangeEvenly spaced values within the half-open interval [start, stop) as one-dimensional array.
fnemptyUninitialized tensor having a specified shape.
fnempty_likeUninitialized tensor with the same shape as an input tensor.
fneyeReturns a two-dimensional array with ones on the kth diagonal and zeros elsewhere.
fnfullNew tensor having a specified shape and filled with given value.
fnfull_likeNew tensor filled with given value and having the same shape as an input tensor.
fnlinspaceEvenly spaced numbers over a specified interval.
fnonesNew tensor filled with ones and having a specified shape.
fnones_likeNew tensor filled with ones and having the same shape as an input tensor.
fnzerosNew tensor filled with zeros and having a specified shape.
fnzeros_likeNew tensor filled with zeros and having the same shape as an input tensor.
fntrilReturns the lower triangular part of a matrix (or a stack of matrices) x.
fntriuReturns the upper triangular part of a matrix (or a stack of matrices) x.

§Basic Operations

§Unary functions

§Binary functions

NOTE: rem can be only called by usual function (rt::rem if you have used rstsr_core::prelude::rt), but not trait function Rem::rem or operator % (which is overrided for matmul).

Trait function calls like associated methods, so we also do not recommend usage of tensor.rem(&other).

§Matrix Multiply

Matrix multiply is implemented in many ways. The most useful way is function matmul and operator %.

NOTE: Matrix multiplication can also called by trait function Rem::rem, but this is strongly not recommended.

Trait function calls like associated methods, so we also do not recommend usage of tensor.rem(&other).

§Common Functions

§Unary functions

abs, acos, acosh, asin, asinh, atan, atanh, ceil, conj, cos, cosh, exp, expm1, floor, imag, inv, is_finite, is_inf, is_nan, log, log10, log2, real, round, sign, signbit, sin, sinh, sqrt, square, tan, tanh, trunc

§Binary functions

atan2, copysign, eq/equal, floor_divide, ge/greater_equal, gt/greater, hypot, le/less_equal, lt/less, log_add_exp, maximum, minimum, ne/not_equal, pow

§Statistical functions

max, mean, min, prod, std, sum, var

§Sorting, searching and counting functions

argmin, argmax, unraveled_argmin, unraveled_argmax

§Developer Area

The above listings of API specifications are mostly for either user usage, or clarafication of most important aspects of the design of RSTSR.

However, there still leaves many public APIs not fully documented or not listed above. Some of them are exposed as developer interfaces.

This part of documentation is under construction.