Skip to content
This repository has been archived by the owner on Jan 10, 2023. It is now read-only.

Bridge Python numpy.ndarray to Array and Tensor #30

Closed
dan-zheng opened this issue May 4, 2018 · 2 comments
Closed

Bridge Python numpy.ndarray to Array and Tensor #30

dan-zheng opened this issue May 4, 2018 · 2 comments

Comments

@dan-zheng
Copy link

dan-zheng commented May 4, 2018

From mailing list discussion: https://groups.google.com/a/tensorflow.org/forum/#!topic/swift/0de3S72qMTU

It would be nice to add initializers that bridge Python numpy.ndarray (as PyValue) to Swift Array and Tensor.

The implementation should use the raw NumPy data pointer via arr.__array_interface__["data"] for efficiency:

>>> import numpy as np
>>> arr = np.zeros(5)
>>> arr.__array_interface__
{'data': (6245613920, False), 'strides': None, 'descr': [('', '<f8')], 'typestr': '<f8', 'shape': (5,), 'version': 3}

Here is a sample skeleton for a Tensor bridge:

extension Tensor {
    // Failable initializer.
    public init?(_ numpyArray: PyValue) {
        // 1. Check if input is a NumPy array.
        // 2. Check if the array's dtype matches the `Scalar` type
        //    (e.g. `np.float32` and `Float`).
        // 3. Extract info from `__array_interface__` and convert to Tensor.
        self.init(shape: ..., scalars: ...)
    }
}

Something to consider is how to handle bridging higher dimensional numpy.ndarray instances to Array. It makes sense for the bridging initializer to fail when the numpy.ndarray instance is not 1-D.

@rxwei
Copy link

rxwei commented May 4, 2018

In the skeleton, please use an initializer self.init(shape: ..., scalars: ...), not a self assignment.

@rxwei
Copy link

rxwei commented May 14, 2018

Moved to SR-7675.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants