C++ multidimensional arrays in the spirit of the STL
This library provides a multidimensional array class for C++, with the following design goals:
The library uses some ideas established in other existing projects, such as numpy, Halide, and Eigen. Array shapes are specified as a list of N dimensions, where each dimension has parameters such as an extent and a stride. Array references and objects use shape objects to map N-dimensional indices to a flat index. N-dimensional indices are mapped to flat offsets with the following formula:
flat_offset = (x0 - min0)*stride0 + (x1 - min1)*stride1 + ... + (xN - minN)*strideNwhere:
xN are the indices in each dimension.minN are the mins in each dimension. The min is the value of the first in-range index in this dimension (the max is minN + extentN - 1).strideN are the distances in the flat offsets between elements in each dimension.Arrays efficiently support advanced manipulations like cropping, slicing, and splitting arrays and loops, all while preserving compile-time constant parameters when possible. Although it is a heavily templated library, incorrect usage generates informative and helpful error messages. Typically, an issue will result in only one error message, located at the site of the problem in user code. This is something we test for.
Many other libraries offering multi-dimensional arrays or tensors allow compile-time constant shapes. However, most if not all of them only allow either all of the shape parameters to be compile-time constant, or none of them. This is really limiting; often only a few key parameters of a shape need to be compile-time constant for performance, while other dimensions need flexibility to accommodate runtime-valued shape parameters. Some examples of this are:
Some other features of the library are:
__device__ functions.For more detailed documentation, see the generated documentation.
The basic types provided by the library are:
dim, a description of a single dimension. The template parameters specify a compile-time constant min, extent, or stride, or are dynamic (meaning unknown) and are specified at runtime.shape, a description of multiple dimensions. Dim0 is referred to as the innermost dimension.array, a container following the conventions of std::vector where possible. This container manages the allocation of a buffer associated with a Shape.array_ref, a wrapper for addressing existing memory with a shape Shape.To define an array, define a shape type, and use it to define an array object:
using my_3d_shape_type = shape, dim<>, dim<>>;
constexpr int width = 16;
constexpr int height = 10;
constexpr int depth = 3;
my_3d_shape_type my_3d_shape(width, height, depth);
array my_array(my_3d_shape);General shapes and arrays like this have the following built-in aliases:
shape_of_rank, an N-dimensional shape.array_ref_of_rank and array_of_rank, N-dimensional arrays with a shape of shape_of_rank.Accessing array or array_ref is done via operator(...) and operator[index_type].
There are both variadic and index_type overloads of operator().
index_type is a specialization of std::tuple defined by shape (and array and array_ref), e.g. my_3d_shape_type::index_type.
for (int z = 0; z `.
The default implementation of `shape_traits::for_each_index` iterates over the innermost dimension as the innermost loop, and proceeds in order to the outermost dimension.
```c++
my_3d_shape_type my_shape(2, 2, 2);
for_all_indices(my_shape, [](int x, int y, int z) {
std::cout ::for_each_value` iterates over a dynamically optimized shape.
The order will vary depending on the properties of the shape.
There are overloads of `for_all_indices` and `for_each_index` accepting a permutation to indicate the loop order. In this example, the permutation `` iterates over the `z` dimension as the innermost loop, then `x`, then `y`.
```c++
for_all_indices(my_shape, [](int x, int y, int z) {
std::cout ,
dim<>,
dim<>>;
array my_dense_array({16, 3, 3});
for (auto x : my_dense_array.x()) {
// The compiler knows that each loop iteration accesses
// elements that are contiguous in memory for contiguous x.
my_dense_array(x, y, z) = 0;
}A dimension with unknown min and extent, and stride 1, is common enough that it has a built-in alias dense_dim<>, and shapes with a dense first dimension are common enough that shapes and arrays have the following built-in aliases:
dense_shape, an N-dimensional shape with the first dimension being dense.dense_array_ref and dense_array, N-dimensional arrays with a shape of dense_shape.There are other common examples that are easy to support. A very common array is an image where 3-channel RGB or 4-channel RGBA pixels are stored together in a 'chunky' format.
template
using chunky_image_shape = shape,
dim<>,
dense_dim>;
array> my_chunky_image({1920, 1080, {}});strided_dim<> is another alias for dim<> where the min and extent are unknown, and the stride may be a compile-time constant.
image.h is a small helper library of typical image shape and object types defined using arrays, including chunky_image_shape.
Another common example is matrices indexed (row, column) with the column dimension stored densely:
using matrix_shape = shape, dense_dim<>>;
array my_matrix({10, 4});
for (auto i : my_matrix.i()) {
for (auto j : my_matrix.j()) {
// This loop ordering is efficient for this type.
my_matrix(i, j) = 0.0;
}
}There are also many use cases for matrices with small constant sizes.
This library provides auto_allocator, an std::allocator compatible allocator that only allocates buffers of N small fixed sized objects with automatic storage.
This makes it possible to define a small matrix type that will not use any dynamic memory allocation:
template
using small_matrix_shape = shape,
dense_dim>;
template
using small_matrix = array, auto_allocator>;
small_matrix my_small_matrix;
// my_small_matrix is only one fixed size allocation, no new/delete calls
// happen. sizeof(small_matrix) = sizeof(float) * 4 * 4 + (overhead)matrix.h is a small helper library of typical matrix shape and object types defined using arrays, including the examples above.
Shapes and arrays can be sliced and cropped using interval objects, which are similar to dim<>s.
They can have either a compile-time constant or runtime valued min and extent.
range(begin, end) is a helper functions to construct an interval.
// Slicing
array_ref_of_rank channel1 = my_array(_, _, 1);
array_ref_of_rank row4_channel2 = my_array(_, 4, 2);
// Cropping
array_ref_of_rank top_left = my_array(interval<>{0, 2}, interval<>{0, 4}, _);
array_ref_of_rank center_channel0 = my_array(interval<>{1, 2}, interval<>{2, 4}, 0);The _ or all constants are placeholders indicating the entire dimension should be preserved.
Dimensions that are sliced are removed from the shape of the array.
When iterating a dim, it is possible to split it first by either a compile-time constant or a runtime-valued split factor.
A split dim produces an iterator range that produces interval<> objects.
This allows easy tiling of algorithms:
constexpr index_t x_split_factor = 3;
const index_t y_split_factor = 5;
for (auto yo : split(my_array.y(), y_split_factor)) {
for (auto xo : split(my_array.x())) {
auto tile = my_array(xo, yo, _);
for (auto x : tile.x()) {
// The compiler knows this loop has a fixed extent x_split_factor!
tile(x, y, z) = x;
}
}
}Both loops have extents that are not divided by their split factors.
To avoid generating an array_ref referencing data out of bounds of the original array, the split iterators modify the last iteration.
The behavior of each kind of split is different:
yo can vary, it is reduced on the last iteration. This strategy can accommodate dimensions of any extent.xo must be a constant, the last iteration will be shifted to overlap the previous iteration. This strategy requires the extent of the dimension being split is greater than the split factor (but not a multiple!)Compile-time constant split factors produce ranges with compile-time extents, and shapes and arrays cropped with these ranges will have a corresponding dim<> with a compile-time constant extent.
This allows potentially significant optimizations to be expressed relatively easily!
The ein_reduce.h header provides Einstein notation reductions and summation helpers, similar to np.einsum or tf.einsum.
These are zero-cost abstractions for describing loops that allow expressing a wide variety of array operations.
Einstein notation expression operands are constructed using the ein(x) helper function, where x can be any callable object, including an array<> or array_ref<>.
i, j, ... are constexpr integers indicating which dimensions of the reduction operation are used to evaluate x.
Therefore, the number of arguments of x must match the number of dimensions provided to ein.
Operands can be combined into larger expressions using typical binary operators.
Einstein notation expressions can be evaluated using one of the following functions:
ein_reduce(expression), evaluate an arbitrary Einstein notation expression.lhs = make_ein_sum(rhs), evaluate the summation ein(lhs) += rhs, and return lhs. The shape of lhs is inferred from the expression.Here are some examples using these reduction operations to compute summations:
// Name the dimensions we use in Einstein reductions.
enum { i = 0, j = 1, k = 2, l = 3 };
// Dot product dot1 = dot2 = x.y:
vector x({10});
vector y({10});
float dot1 = make_ein_sum(ein(x) * ein(y));
float dot2 = 0.0f;
ein_reduce(ein(dot2) += ein(x) * ein(y));
// Matrix multiply C1 = C2 = A*B:
matrix A({10, 10});
matrix B({10, 15});
matrix C1({10, 15});
fill(C1, 0.0f);
ein_reduce(ein(C1) += ein(A) * ein(B));
auto C2 = make_ein_sum(ein(A) * ein(B));We can use arbitrary functions as expression operands:
// Cross product array crosNo open issues yet, or sync has not completed.