Skip to content

[Feature Request] Support tensor creation from objects that implement the __array__ interface #51156

@rsokl

Description

@rsokl

🚀 Feature

It would be great for torch.tensor(obj), torch.from_numpy(obj), and other tensor-creation functions to check obj.__array__() before raising an error that obj is of the wrong type.

I'd be happy to give this a shot.

Motivation

NumPy provides a standard way for a class to expose a numpy.ndarray so that NumPy functions like asarray can know how to cast it to an array. This standard is for the class to implement an __array__() method that returns a standard numpy.ndarray .

This standard makes it really convenient for non-ndarray classes to nonetheless interface nicely with NumPy, xarray, and other array-based libraries.

import numpy as np
import xarray as xr
import torch as tr

class MyData:
    # This is just a silly toy example
    def __array__(self, dtype=None):
        return np.array([1., 2.], dtype=np.float32)

my_data = MyData()

We can make a ndarray out of my_data...

>>> np.asarray(my_data)
array([1., 2.], dtype=float32)

my_data can even take the form of an xarray-DataArray

>>> xr.DataArray(my_data)
<xarray.DataArray (dim_0: 2)>
array([1., 2.], dtype=float32)
Dimensions without coordinates: dim_0

But my_data cannot easily be made a tensor!

>>> tr.tensor(my_data)
RuntimeError: Could not infer dtype of MyData

>>> tr.from_numpy(my_data)
TypeError: expected np.ndarray (got MyData)

>>> tr.as_tensor(my_data)
RuntimeError: Could not infer dtype of MyData

Pitch

I would be happy to take a swing at this as long as this feature can be implemented without leaving the pure-Python side of things.

cc @mruberry @rgommers @heitorschueroff

Metadata

Metadata

Assignees

Labels

function requestA request for a new function or the addition of new arguments/modes to an existing function.module: numpyRelated to numpy support, and also numpy compatibility of our operatorsneeds designWe want to add this feature but we need to figure out how firsttriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions