Expose the System.Numerics.Tensors interchange types as interfaces
Rationale
We would like to expose a set of types that allow exchange and interop between the various tensor frameworks. Today, the types that enable this are a set of classes with an abstract base and were taken from the initial investigations in corefxlab. However, these types put an unnecessary burden on each framework exposing a Tensor type in that they either need to extend these types themselves or they need to expose additional APIs that accept this type for interop/exchange to happen. It also requires that these types be implemented as classes, which may cause a performance hit as the common case is that the frameworks instead often implement these types as structs wrapping some backing memory.
After a number of discussions, it was determined that we should move forward with exposing these types as a set of interfaces instead. This allows the existing frameworks to easily extend their existing types (whether they are classes or structs) to be compatible with the new interface types. It also allows library authors to easily support any tensor type will still allowing them to easily get the framework specific type or to efficiently specialize the handling for specific input types.
Proposed APIs
The following is the new proposed surface area. The existing types (which are not listed, for simplicity) would be removed and would no longer be available.
namespace System.Numerics.Tensors
{
public interface ITensor<T>
{
ReadOnlySpan<int> Dimensions { get; }
int Rank { get; }
T this[params int[] indices] { get; set; }
T this[ReadOnlySpan<int> indices] { get; set; }
ITensor<T> Slice(int[] startIndices, int[] lengths);
ITensor<T> Reshape(ReadOnlySpan<int> dimensions);
}
public interface IDenseTensor<T> : ITensor<T>
{
Span<T> Buffer { get; }
int ElementCount { get; }
bool IsColumnMajor { get; }
ReadOnlySpan<int> Strides { get; }
void Fill(T value);
ISparseTensor<T> ToSparseTensor();
}
public interface ISparseTensor<T> : ITensor<T>
{
int NonZeroCount { get; }
Span<T> GetNonZeroValues();
Span<int> GetNonZeroIndices();
IDenseTensor<T> ToDenseTensor();
}
}
Additional Details
Some generale notes:
- We decided that compressed sparse tensors were not worth exposing at this time.
- We are not going to be exposing the
CloneorCloneEmptymethods. This will require users to make clones are create new instances using concrete types. - We may consider also exposing a primitive struct implementation for these interfaces, but that is a separate proposal.
Some notes about ITensor<T>:
- We determined
ITensor<T>should not implementIList<T>orICollection<T>as they do not properly expose the multi-dimensional concept of a tensor. Rankis a convenience overload forDimensions.Length. However, many frameworks expose this as a specific concept.- The indexer that takes a
ROSpan<int>could be madeparamswith the proposed C# Language Feature: https://github.com/dotnet/csharplang/pull/2293 Reshapeis exposed here as many other frameworks also expose it as a base method due to it also being applicable to sparse tensors.
Some notes about IDenseTensor<T>:
IsColumnMajoris not the best name since it doesn't necessarily map cleanly to multiple dimensions. However,System.Arrayalready uses the same name.
Open Questions
Some general open questions:
- Should we expose the concept of a
IReadOnlyTensor<T>?
Some open questions about ITensor<T>:
- Should
ITensor<T>implementIEnumerable<T>and if so, what would it mean for a sparse tensor?- If no, should we make
IDenseTensor<T>implement it instead?
- If no, should we make
- Should
ITensor.Dimensionsbe calledShapeinstead? Other frameworks exposing this asShapeoften have a concete type and may carry additional information, such as a name. - Ideally the
ITensor<T>.Slicemethod would takeparams Range[] ranges. However, this type will benetstandard2.1only. An alternative to the proposed API would be to take aparams (int startIndex, int length)[] rangesinstead.
Some open questions about IDenseTensor<T>:
- Is returning a
Span<T>forBuffersufficient or should it beMemory<T>instead?- What if the underlying buffer is larger than
int.MaxValue? - Maybe we should return
Memory<T>and have some kind of efficientref struct TensorViewfor the case where you want to materialize and reuse aSpan<T>. This doesn't play nicely when the underlying element count can change, however.
- What if the underlying buffer is larger than
- Do we need to expose
ElementCountfor convenience or should we tell users to just get the product of its dimensions?- Should
ElementCountreturn a long since the combined length of all dimensions could be larger thanint.MaxValue? - Should this be exposed on
ITensor<T>instead and what would it mean for a sparse tensor if it was (i.e. is it the product of the dimensions or is it the non-zero element count)?
- Should
- Should we expose
ToSparseTensoronly here or move it toITensor<T>? The latter would allow users to avoid type checks if they know they need or want aSparseTensor. Otherwise, they need to basically doISparseTensor<T> sparseTensor = (tensor is IDenseTensor<T> denseTensor) ? denseTensor.ToSparseTensor() : (ISparseTensor<T>)(tensor);, which would throw if someone inherited fromITensordirectly/separately. - Should we expose a mechanism for getting/setting a value using the linear index?
Some open questions about ISparseTensor<T>:
- Should
GetNonZeroValuesandGetNonZeroIndicesbe separate or should we provide a mechanism to get both at once? ToDenseTensorhas the same open question asIDenseTensor.ToSparseTensor
CC. @danmosemsft, @eerhardt.
CC. @terrajobst. This will require a dedicated session to review (after I finish get sign-off from the partner teams on the proposal).
CC. @interesaaat, @markusweimer, @ericstj
Span<int> GetNonZeroIndices();
I assume these are "linearized" indices? Do we have any convenience APIs planned to get the index collection in dimensions from a "linearized" index?
Span<T> GetNonZeroValues();Span<int> GetNonZeroIndices();
I wonder if Span helps or hurts here. If the values and indices aren't stored in a contiguous piece of memory for a SparseTensor, it would force implementers to copy the values/indices, right?
Should we expose a mechanism for getting/setting a value using the linear index?
We do for DenseTensors, right? IDenseTensor.Buffer[i] will be the linear index.
IsColumnMajor is not the best name since it doesn't necessarily map cleanly to multiple dimensions. However, System.Array already uses the same name.
Where does System.Array expose this name? I agree IsColumnMajor is the most understandable name for this property, but I am just missing where it is used in System.Array.
CC. @migueldeicaza
Span<T> GetNonZeroValues();Span<int> GetNonZeroIndices();I wonder if
Spanhelps or hurts here. If the values and indices aren't stored in a contiguous piece of memory for a SparseTensor, it would force implementers to copy the values/indices, right?
This is a good point. I look at these more as IEnumerables.
ITensor
Slice(int[] startIndices, int[] lengths);
I wonder if we could instead introduce a TensorRange type here. Someday it could maybe be implicitly convertible to/from System.Range.
I like having an abstraction over actual tensor implementations so that in theory one could differentiate between "views" onto a tensor and actual "materialized" tensors.
As i explained in https://github.com/dotnet/corefx/issues/34525#issuecomment-470736431, my use case at the moment involves using a lot of operation on matrices and the first perf issues hit occur because of copying that needs to be done when performing operations. Most of them can be done in-place but my goal would be to have abstract views over them that would be materialized when needed - similar to how IEnumerable<T> works with LINQ (where materialization is done via ToList()/ToArray()). This would allow for more composable and reusable implementations for part of algorithms. E.g. I don't really need to allocate more than n*m memory when calculating norm(1 - 2*a + b), but 2*a and b could be results from other algorithms that i want to reuse.
(btw i keep IList<Matrix<double>> in a few places so desperately awaiting public tensors and math functions for them ^^)
So personally I like seing an abstraction over tensors that could internally trigger materialization when needed or hide a mathematical operation / slice behind the indexer while keeping a reference to the source tensor.
regarding ISparseTensor<T> ToSparseTensor() and IDenseTensor<T> ToDenseTensor():
I don't think that any implementation of a dense or sparse tensor should also be required to implement conversion between dense and sparse tensors. For easy conversion, there should be extension methods that create the default types - similar to how ToList() / ToArray() / ToHashSet() exist on IEnumerable<T>. The implementation could then have a few optimizations tensor is SlicedDenseTensor<T> for system provided implementations.
Notes:
- Currently user does not know if they need to convert dense to sparse. Moving
int NonZeroCount { get; }toTensor<T>- that would allow user to decide on whether they need to convert toSparseTensor<T> - Multi-dimensional sparse tensor: how is
Span<T> GetNonZeroValues();
Span<int> GetNonZeroIndices();
usable in multiple dimensions? Suggest return tensors of values
3. Consider having ReadOnlyTensor<> as default type as some native or vbuffer backing types might not allow free modification of underlying data.
Notes are here.
IsColumnMajor doesn't make a lot of sense to me. Could we remove it? The definition of column is quite clear to a matrix, but what is a column in a tensor? Why is it called column rather than row?
(Repeating a couple of the earlier questions): How are multi-dimensional sparse-tensors handled? Is the index-value a linearized index-value?
@tannergooding should this be closed?
Yes, this was replaced by the modern tensor API we did ship