runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Expose the System.Numerics.Tensors interchange types as interfaces

Open tannergooding opened this issue 7 years ago • 15 comments

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 Clone or CloneEmpty methods. 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 implement IList<T> or ICollection<T> as they do not properly expose the multi-dimensional concept of a tensor.
  • Rank is a convenience overload for Dimensions.Length. However, many frameworks expose this as a specific concept.
  • The indexer that takes a ROSpan<int> could be made params with the proposed C# Language Feature: https://github.com/dotnet/csharplang/pull/2293
  • Reshape is 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>:

  • IsColumnMajor is not the best name since it doesn't necessarily map cleanly to multiple dimensions. However, System.Array already uses the same name.

tannergooding avatar Mar 04 '19 22:03 tannergooding

Open Questions

Some general open questions:

  • Should we expose the concept of a IReadOnlyTensor<T>?

Some open questions about ITensor<T>:

  • Should ITensor<T> implement IEnumerable<T> and if so, what would it mean for a sparse tensor?
    • If no, should we make IDenseTensor<T> implement it instead?
  • Should ITensor.Dimensions be called Shape instead? Other frameworks exposing this as Shape often have a concete type and may carry additional information, such as a name.
  • Ideally the ITensor<T>.Slice method would take params Range[] ranges. However, this type will be netstandard2.1 only. An alternative to the proposed API would be to take a params (int startIndex, int length)[] ranges instead.

Some open questions about IDenseTensor<T>:

  • Is returning a Span<T> for Buffer sufficient or should it be Memory<T> instead?
    • What if the underlying buffer is larger than int.MaxValue?
    • Maybe we should return Memory<T> and have some kind of efficient ref struct TensorView for the case where you want to materialize and reuse a Span<T>. This doesn't play nicely when the underlying element count can change, however.
  • Do we need to expose ElementCount for convenience or should we tell users to just get the product of its dimensions?
    • Should ElementCount return a long since the combined length of all dimensions could be larger than int.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 we expose ToSparseTensor only here or move it to ITensor<T>? The latter would allow users to avoid type checks if they know they need or want a SparseTensor. Otherwise, they need to basically do ISparseTensor<T> sparseTensor = (tensor is IDenseTensor<T> denseTensor) ? denseTensor.ToSparseTensor() : (ISparseTensor<T>)(tensor);, which would throw if someone inherited from ITensor directly/separately.
  • Should we expose a mechanism for getting/setting a value using the linear index?

Some open questions about ISparseTensor<T>:

  • Should GetNonZeroValues and GetNonZeroIndices be separate or should we provide a mechanism to get both at once?
  • ToDenseTensor has the same open question as IDenseTensor.ToSparseTensor

tannergooding avatar Mar 04 '19 22:03 tannergooding

CC. @danmosemsft, @eerhardt.

tannergooding avatar Mar 04 '19 22:03 tannergooding

CC. @terrajobst. This will require a dedicated session to review (after I finish get sign-off from the partner teams on the proposal).

tannergooding avatar Mar 04 '19 22:03 tannergooding

CC. @interesaaat, @markusweimer, @ericstj

tannergooding avatar Mar 04 '19 22:03 tannergooding

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.

eerhardt avatar Mar 05 '19 00:03 eerhardt

CC. @migueldeicaza

tannergooding avatar Mar 05 '19 21:03 tannergooding

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?

This is a good point. I look at these more as IEnumerables.

interesaaat avatar Mar 06 '19 22:03 interesaaat

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.

eerhardt avatar Mar 08 '19 15:03 eerhardt

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.

dasMulli avatar Mar 12 '19 12:03 dasMulli

Notes:

  1. Currently user does not know if they need to convert dense to sparse. Moving int NonZeroCount { get; } to Tensor<T> - that would allow user to decide on whether they need to convert to SparseTensor<T>
  2. 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.

glebuk avatar Mar 12 '19 18:03 glebuk

Notes are here.

terrajobst avatar Mar 12 '19 21:03 terrajobst

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?

wschin avatar Mar 14 '19 17:03 wschin

(Repeating a couple of the earlier questions): How are multi-dimensional sparse-tensors handled? Is the index-value a linearized index-value?

gramalingam avatar Apr 24 '19 19:04 gramalingam

@tannergooding should this be closed?

terrajobst avatar Jan 07 '25 17:01 terrajobst

Yes, this was replaced by the modern tensor API we did ship

tannergooding avatar Jul 23 '26 18:07 tannergooding